rustis 0.19.3

Redis async 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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
use crate::{
    client::{PreparedCommand, prepare_command},
    resp::{Response, Value, cmd, serialize_flag},
};
use serde::{
    Deserialize, Serialize,
    de::{self, value::SeqAccessDeserializer},
};
use smallvec::SmallVec;
use std::{collections::HashMap, fmt};

/// A group of Redis commands related to [`Time Series`](https://redis.io/docs/stack/timeseries/)
///
/// # See Also
/// [Time Series Commands](https://redis.io/commands/?group=timeseries)
pub trait TimeSeriesCommands<'a>: Sized {
    /// Append a sample to a time series
    ///
    /// # Arguments
    /// * `key` - key name for the time series.
    /// * `timestamp` - UNIX sample timestamp in milliseconds or `*` to set the timestamp according to the server clock.
    /// * `values` - numeric data value of the sample. The double number should follow [`RFC 7159`](https://tools.ietf.org/html/rfc7159)
    ///   (JSON standard). In particular, the parser rejects overly large values that do not fit in binary64. It does not accept `NaN` or `infinite` values.
    ///
    /// # Return
    /// The UNIX sample timestamp in milliseconds
    ///
    /// # Notes
    /// * When specified key does not exist, a new time series is created.
    /// * if a [`COMPACTION_POLICY`](https://redis.io/docs/stack/timeseries/configuration/#compaction_policy) configuration parameter is defined,
    ///   compacted time series would be created as well.
    /// * If timestamp is older than the retention period compared to the maximum existing timestamp, the sample is discarded and an error is returned.
    /// * When adding a sample to a time series for which compaction rules are defined:
    ///   * If all the original samples for an affected aggregated time bucket are available,
    ///     the compacted value is recalculated based on the reported sample and the original samples.
    ///   * If only a part of the original samples for an affected aggregated time bucket is available
    ///     due to trimming caused in accordance with the time series RETENTION policy, the compacted value
    ///     is recalculated based on the reported sample and the available original samples.
    ///   * If the original samples for an affected aggregated time bucket are not available due to trimming
    ///     caused in accordance with the time series RETENTION policy, the compacted value bucket is not updated.
    ///  * Explicitly adding samples to a compacted time series (using [`ts_add`](TimeSeriesCommands::ts_add), [`ts_madd`](TimeSeriesCommands::ts_madd),
    ///    [`ts_incrby`](TimeSeriesCommands::ts_incrby), or [`ts_decrby`](TimeSeriesCommands::ts_decrby)) may result
    ///    in inconsistencies between the raw and the compacted data. The compaction process may override such samples.
    ///
    /// # Complexity
    /// If a compaction rule exits on a time series, the performance of `ts_add` can be reduced.
    /// The complexity of `ts_add` is always `O(M)`, where `M` is the number of compaction rules or `O(1)` with no compaction.
    ///
    /// # See Also
    /// * [<https://redis.io/commands/ts.add/>](https://redis.io/commands/ts.add/)
    #[must_use]
    fn ts_add(
        self,
        key: impl Serialize,
        timestamp: TsTimestamp,
        value: f64,
        options: TsAddOptions,
    ) -> PreparedCommand<'a, Self, u64> {
        prepare_command(
            self,
            cmd("TS.ADD")
                .key(key)
                .arg(timestamp)
                .arg(value)
                .arg(options),
        )
    }

    /// Update the retention, chunk size, duplicate policy, and labels of an existing time series
    ///
    /// # Arguments
    /// * `key` - key name for the time series.
    /// * `options` - options to alter the existing time series. [`encoding`](TsCreateOptions::encoding) cannot be used on this command.
    ///
    /// # Notes
    /// This command alters only the specified element.
    /// For example, if you specify only retention and labels, the chunk size and the duplicate policy are not altered.
    ///
    /// # See Also
    /// * [<https://redis.io/commands/ts.alter/>](https://redis.io/commands/ts.alter/)
    #[must_use]
    fn ts_alter(
        self,
        key: impl Serialize,
        options: TsCreateOptions,
    ) -> PreparedCommand<'a, Self, ()> {
        prepare_command(self, cmd("TS.ALTER").key(key).arg(options))
    }

    /// Create a new time series
    ///
    /// # Arguments
    /// * `key` - key name for the time series.
    ///
    /// # Notes
    /// * If a key already exists, you get a Redis error reply, TSDB: key already exists.
    ///   You can check for the existence of a key with the [`exists`](crate::commands::GenericCommands::exists) command.
    /// * Other commands that also create a new time series when called with a key that does not exist are
    ///   [`ts_add`](TimeSeriesCommands::ts_add), [`ts_incrby`](TimeSeriesCommands::ts_incrby), and [`ts_decrby`](TimeSeriesCommands::ts_decrby).
    ///
    /// # See Also
    /// * [<https://redis.io/commands/ts.create/>](https://redis.io/commands/ts.create/)
    #[must_use]
    fn ts_create(
        self,
        key: impl Serialize,
        options: TsCreateOptions,
    ) -> PreparedCommand<'a, Self, ()> {
        prepare_command(self, cmd("TS.CREATE").key(key).arg(options))
    }

    /// Create a compaction rule
    ///
    /// # Arguments
    /// * `src_key` - key name for the source time series.
    /// * `dst_key` - key name for destination (compacted) time series.
    ///   It must be created before `ts_createrule` is called.
    /// * `aggregator` - aggregates results into time buckets by taking an aggregation type
    /// * `bucket_duration` - duration of each aggregation bucket, in milliseconds.
    /// * `options` - See [`TsCreateRuleOptions`](TsCreateRuleOptions)
    ///
    /// # Notes
    /// * Only new samples that are added into the source series after the creation of the rule will be aggregated.
    /// * Calling `ts_createrule` with a nonempty `dst_key` may result in inconsistencies between the raw and the compacted data.
    /// * Explicitly adding samples to a compacted time series (using [`ts_add`](TimeSeriesCommands::ts_add),
    ///   [`ts_madd`](TimeSeriesCommands::ts_madd), [`ts_incrby`](TimeSeriesCommands::ts_incrby), or [`ts_decrby`](TimeSeriesCommands::ts_decrby))
    ///   may result in inconsistencies between the raw and the compacted data. The compaction process may override such samples.
    /// * If no samples are added to the source time series during a bucket period. no compacted sample is added to the destination time series.
    /// * The timestamp of a compacted sample added to the destination time series is set to the start timestamp the appropriate compaction bucket.
    ///   For example, for a 10-minute compaction bucket with no alignment, the compacted samples timestamps are `x:00`, `x:10`, `x:20`, and so on.
    ///
    /// # See Also
    /// * [<https://redis.io/commands/ts.createrule/>](https://redis.io/commands/ts.createrule/)
    #[must_use]
    fn ts_createrule(
        self,
        src_key: impl Serialize,
        dst_key: impl Serialize,
        aggregator: TsAggregationType,
        bucket_duration: u64,
        options: TsCreateRuleOptions,
    ) -> PreparedCommand<'a, Self, ()> {
        prepare_command(
            self,
            cmd("TS.CREATERULE")
                .key(src_key)
                .key(dst_key)
                .arg("AGGREGATION")
                .arg(aggregator)
                .arg(bucket_duration)
                .arg(options),
        )
    }

    /// Decrease the value of the sample with the maximum existing timestamp,
    /// or create a new sample with a value equal to the value of the sample with the maximum existing timestamp with a given decrement
    ///
    /// # Arguments
    /// * `key` - key name for the time series.
    /// * `value` - numeric data value of the sample
    /// * `options` - See [`TsIncrByDecrByOptions`](TsIncrByDecrByOptions)
    ///
    /// # Notes
    /// * When specified key does not exist, a new time series is created.
    /// * You can use this command as a counter or gauge that automatically gets history as a time series.
    /// * Explicitly adding samples to a compacted time series (using [`ts_add`](TimeSeriesCommands::ts_add),
    ///   [`ts_madd`](TimeSeriesCommands::ts_madd), [`ts_incrby`](TimeSeriesCommands::ts_incrby),
    ///   or [`ts_decrby`](TimeSeriesCommands::ts_decrby)) may result in inconsistencies between the raw and the compacted data.
    ///   The compaction process may override such samples.
    ///
    /// # See Also
    /// * [<https://redis.io/commands/ts.decrby/>](https://redis.io/commands/ts.decrby/)
    #[must_use]
    fn ts_decrby(
        self,
        key: impl Serialize,
        value: f64,
        options: TsIncrByDecrByOptions,
    ) -> PreparedCommand<'a, Self, ()> {
        prepare_command(self, cmd("TS.DECRBY").key(key).arg(value).arg(options))
    }

    /// Delete all samples between two timestamps for a given time series
    ///
    /// # Arguments
    /// * `key` - key name for the time series.
    /// * `from_timestamp` - start timestamp for the range deletion.
    /// * `to_timestamp` - end timestamp for the range deletion.
    ///
    /// # Return
    /// The number of samples that were removed.
    ///
    /// # Notes
    /// The given timestamp interval is closed (inclusive),
    /// meaning that samples whose timestamp equals the `from_timestamp` or `to_timestamp` are also deleted.
    ///
    /// # See Also
    /// * [<https://redis.io/commands/ts.del/>](https://redis.io/commands/ts.del/)
    #[must_use]
    fn ts_del(
        self,
        key: impl Serialize,
        from_timestamp: u64,
        to_timestamp: u64,
    ) -> PreparedCommand<'a, Self, usize> {
        prepare_command(
            self,
            cmd("TS.DEL").key(key).arg(from_timestamp).arg(to_timestamp),
        )
    }

    /// Delete a compaction rule
    ///
    /// # Arguments
    /// * `src_key` - key name for the source time series.
    /// * `dst_key` - key name for destination (compacted) time series.
    ///
    /// # Notes
    /// This command does not delete the compacted series.
    ///
    /// # See Also
    /// * [<https://redis.io/commands/ts.deleterule/>](https://redis.io/commands/ts.deleterule/)
    #[must_use]
    fn ts_deleterule(
        self,
        src_key: impl Serialize,
        dst_key: impl Serialize,
    ) -> PreparedCommand<'a, Self, ()> {
        prepare_command(self, cmd("TS.DELETERULE").key(src_key).key(dst_key))
    }

    /// Get the last sample
    ///
    /// # Arguments
    /// * `key` - key name for the time series.
    /// * `options` - See [`TsGetOptions`](TsGetOptions)
    ///
    /// # Return
    /// An option tuple:
    /// * The last sample timestamp, and last sample value, when the time series contains data.
    /// * None, when the time series is empty.
    ///
    /// # See Also
    /// * [<https://redis.io/commands/ts.get/>](https://redis.io/commands/ts.get/)
    #[must_use]
    fn ts_get(
        self,
        key: impl Serialize,
        options: TsGetOptions,
    ) -> PreparedCommand<'a, Self, Option<(u64, f64)>> {
        prepare_command(self, cmd("TS.GET").key(key).arg(options))
    }

    /// Increase the value of the sample with the maximum existing timestamp,
    /// or create a new sample with a value equal to the value of the sample
    /// with the maximum existing timestamp with a given increment
    ///
    /// # Arguments
    /// * `key` - key name for the time series.
    /// * `value` - numeric data value of the sample
    /// * `options` - See [`TsIncrByDecrByOptions`](TsIncrByDecrByOptions)
    ///
    /// # Notes
    /// * When specified key does not exist, a new time series is created.
    /// * You can use this command as a counter or gauge that automatically gets history as a time series.
    /// * Explicitly adding samples to a compacted time series (using [`ts_add`](TimeSeriesCommands::ts_add),
    ///   [`ts_madd`](TimeSeriesCommands::ts_madd), [`ts_incrby`](TimeSeriesCommands::ts_incrby),
    ///   or [`ts_decrby`](TimeSeriesCommands::ts_decrby)) may result in inconsistencies between the raw and the compacted data.
    ///   The compaction process may override such samples.
    ///
    /// # See Also
    /// * [<https://redis.io/commands/ts.incrby/>](https://redis.io/commands/ts.incrby/)
    #[must_use]
    fn ts_incrby(
        self,
        key: impl Serialize,
        value: f64,
        options: TsIncrByDecrByOptions,
    ) -> PreparedCommand<'a, Self, u64> {
        prepare_command(self, cmd("TS.INCRBY").key(key).arg(value).arg(options))
    }

    /// Return information and statistics for a time series.
    ///
    /// # Arguments
    /// * `key` - key name for the time series.
    /// * `debug` - an optional flag to get a more detailed information about the chunks.
    ///
    /// # Return
    /// an instance of [`TsInfoResult`](TsInfoResult)
    ///
    /// # See Also
    /// * [<https://redis.io/commands/ts.info/>](https://redis.io/commands/ts.info/)
    #[must_use]
    fn ts_info(self, key: impl Serialize, debug: bool) -> PreparedCommand<'a, Self, TsInfoResult> {
        prepare_command(self, cmd("TS.INFO").key(key).arg_if(debug, "DEBUG"))
    }

    /// Append new samples to one or more time series
    ///
    /// # Arguments
    /// * `items` - one or more the following tuple:
    ///   * `key` - the key name for the time series.
    ///   * `timestamp` - the UNIX sample timestamp in milliseconds or * to set the timestamp according to the server clock.
    ///   * `value` - numeric data value of the sample (double). \
    ///     The double number should follow [`RFC 7159`](https://tools.ietf.org/html/rfc7159) (a JSON standard).
    ///     The parser rejects overly large values that would not fit in binary64.
    ///     It does not accept `NaN` or `infinite` values.
    ///
    /// # Return
    /// a collection of the timestamps of added samples
    ///
    /// # Notes
    /// * If timestamp is older than the retention period compared to the maximum existing timestamp,
    ///   the sample is discarded and an error is returned.
    /// * Explicitly adding samples to a compacted time series (using [`ts_add`](TimeSeriesCommands::ts_add),
    ///   [`ts_madd`](TimeSeriesCommands::ts_madd), [`ts_incrby`](TimeSeriesCommands::ts_incrby),
    ///   or [`ts_decrby`](TimeSeriesCommands::ts_decrby)) may result in inconsistencies between the raw and the compacted data.
    ///   The compaction process may override such samples.
    ///
    /// # See Also
    /// * [<https://redis.io/commands/ts.madd/>](https://redis.io/commands/ts.madd/)
    #[must_use]
    fn ts_madd<R: Response>(self, items: impl Serialize) -> PreparedCommand<'a, Self, R> {
        prepare_command(
            self,
            cmd("TS.MADD")
                .key_with_step(items, 3)
                .cluster_info(None, None, 3),
        )
    }

    /// Get the last samples matching a specific filter
    ///
    /// # Arguments
    /// * `options` - See [`TsMGetOptions`](TsMGetOptions)
    /// * `filters` - filters time series based on their labels and label values, with these options:
    ///   * `label=value`, where `label` equals `value`
    ///   * `label!=value`, where `label` does not equal `value`
    ///   * `label=`, where `key` does not have label `label`
    ///   * `label!=`, where `key` has label `label`
    ///   * `label=(_value1_,_value2_,...)`, where `key` with label `label` equals one of the values in the list
    ///   * `label!=(value1,value2,...)` where `key` with label `label` does not equal any of the values in the list
    ///
    /// # Return
    /// A collection of [`TsSample`](TsSample)
    ///
    /// # Notes
    /// * When using filters, apply a minimum of one label=value filter.
    /// * Filters are conjunctive. For example, the FILTER `type=temperature room=study`
    ///   means the time series is a temperature time series of a study room.
    ///
    /// # See Also
    /// * [<https://redis.io/commands/ts.mget/>](https://redis.io/commands/ts.mget/)
    #[must_use]
    fn ts_mget<R: Response>(
        self,
        options: TsMGetOptions,
        filters: impl Serialize,
    ) -> PreparedCommand<'a, Self, R> {
        prepare_command(self, cmd("TS.MGET").arg(options).arg("FILTER").arg(filters))
    }

    /// Query a range across multiple time series by filters in forward direction
    ///
    /// # Arguments
    /// * `from_timestamp` - start timestamp for the range query (integer UNIX timestamp in milliseconds)
    ///   or `-` to denote the timestamp of the earliest sample in the time series.
    /// * `to_timestamp` - end timestamp for the range query (integer UNIX timestamp in milliseconds)
    ///   or `+` to denote the timestamp of the latest sample in the time series.
    /// * `options` - See [`TsMRangeOptions`](TsMRangeOptions)
    /// * `filters` - filters time series based on their labels and label values, with these options:
    ///   * `label=value`, where `label` equals `value`
    ///   * `label!=value`, where `label` does not equal `value`
    ///   * `label=`, where `key` does not have label `label`
    ///   * `label!=`, where `key` has label `label`
    ///   * `label=(_value1_,_value2_,...)`, where `key` with label `label` equals one of the values in the list
    ///   * `label!=(value1,value2,...)` where `key` with label `label` does not equal any of the values in the list
    /// * `groupby_options` - See [`TsGroupByOptions`](TsGroupByOptions)
    ///
    /// # Return
    /// A collection of [`TsRangeSample`](TsRangeSample)
    ///
    /// # Notes
    /// * The `ts_mrange` command cannot be part of transaction when running on a Redis cluster.
    ///
    /// # See Also
    /// * [<https://redis.io/commands/ts.mrange/>](https://redis.io/commands/ts.mrange/)
    #[must_use]
    fn ts_mrange<R: Response>(
        self,
        from_timestamp: impl Serialize,
        to_timestamp: impl Serialize,
        options: TsMRangeOptions,
        filters: impl Serialize,
        groupby_options: TsGroupByOptions,
    ) -> PreparedCommand<'a, Self, R> {
        prepare_command(
            self,
            cmd("TS.MRANGE")
                .arg(from_timestamp)
                .arg(to_timestamp)
                .arg(options)
                .arg("FILTER")
                .arg(filters)
                .arg(groupby_options),
        )
    }

    /// Query a range across multiple time series by filters in reverse direction
    ///
    /// # Arguments
    /// * `from_timestamp` - start timestamp for the range query (integer UNIX timestamp in milliseconds)
    ///   or `-` to denote the timestamp of the earliest sample in the time series.
    /// * `to_timestamp` - end timestamp for the range query (integer UNIX timestamp in milliseconds)
    ///   or `+` to denote the timestamp of the latest sample in the time series.
    /// * `options` - See [`TsMRangeOptions`](TsMRangeOptions)
    /// * `filters` - filters time series based on their labels and label values, with these options:
    ///   * `label=value`, where `label` equals `value`
    ///   * `label!=value`, where `label` does not equal `value`
    ///   * `label=`, where `key` does not have label `label`
    ///   * `label!=`, where `key` has label `label`
    ///   * `label=(_value1_,_value2_,...)`, where `key` with label `label` equals one of the values in the list
    ///   * `label!=(value1,value2,...)` where `key` with label `label` does not equal any of the values in the list
    /// * `groupby_options` - See [`TsGroupByOptions`](TsGroupByOptions)
    ///
    /// # Return
    /// A collection of [`TsRangeSample`](TsRangeSample)
    ///
    /// # Notes
    /// * The `ts_mrevrange` command cannot be part of transaction when running on a Redis cluster.
    ///
    /// # See Also
    /// * [<https://redis.io/commands/ts.mrevrange/>](https://redis.io/commands/ts.mrevrange/)
    #[must_use]
    fn ts_mrevrange<R: Response>(
        self,
        from_timestamp: impl Serialize,
        to_timestamp: impl Serialize,
        options: TsMRangeOptions,
        filters: impl Serialize,
        groupby_options: TsGroupByOptions,
    ) -> PreparedCommand<'a, Self, R> {
        prepare_command(
            self,
            cmd("TS.MREVRANGE")
                .arg(from_timestamp)
                .arg(to_timestamp)
                .arg(options)
                .arg("FILTER")
                .arg(filters)
                .arg(groupby_options),
        )
    }

    /// Get all time series keys matching a filter list
    ///
    /// # Arguments
    /// * `filters` - filters time series based on their labels and label values, with these options:
    ///   * `label=value`, where `label` equals `value`
    ///   * `label!=value`, where `label` does not equal `value`
    ///   * `label=`, where `key` does not have label `label`
    ///   * `label!=`, where `key` has label `label`
    ///   * `label=(_value1_,_value2_,...)`, where `key` with label `label` equals one of the values in the list
    ///   * `label!=(value1,value2,...)` where `key` with label `label` does not equal any of the values in the list
    ///
    /// # Return
    /// A collection of keys
    ///
    /// # Notes
    /// * When using filters, apply a minimum of one `label=value` filter.
    /// * `ts_queryindex` cannot be part of a transaction that runs on a Redis cluster.
    /// * Filters are conjunctive. For example, the FILTER `type=temperature room=study`
    ///   means the a time series is a temperature time series of a study room.
    ///
    /// # See Also
    /// * [<https://redis.io/commands/ts.queryindex/>](https://redis.io/commands/ts.queryindex/)
    #[must_use]
    fn ts_queryindex<R: Response>(self, filters: impl Serialize) -> PreparedCommand<'a, Self, R> {
        prepare_command(self, cmd("TS.QUERYINDEX").arg(filters))
    }

    /// Query a range in forward direction
    ///
    /// # Arguments
    /// * `key` - the key name for the time series.
    /// * `from_timestamp` - start timestamp for the range query (integer UNIX timestamp in milliseconds)
    ///   or `-`to denote the timestamp of the earliest sample in the time series.
    /// * `to_timestamp` - end timestamp for the range query (integer UNIX timestamp in milliseconds)
    ///   or `+` to denote the timestamp of the latest sample in the time series.
    /// * `options` - See [`TsRangeOptions`](TsRangeOptions)
    ///
    /// # Return
    /// A collection of keys
    ///
    /// # Notes
    /// * When the time series is a compaction,
    ///   the last compacted value may aggregate raw values with timestamp beyond `to_timestamp`.
    ///   That is because `to_timestamp` only limits the timestamp of the compacted value,
    ///   which is the start time of the raw bucket that was compacted.
    ///
    /// # See Also
    /// * [<https://redis.io/commands/ts.range/>](https://redis.io/commands/ts.range/)
    #[must_use]
    fn ts_range<R: Response>(
        self,
        key: impl Serialize,
        from_timestamp: impl Serialize,
        to_timestamp: impl Serialize,
        options: TsRangeOptions,
    ) -> PreparedCommand<'a, Self, R> {
        prepare_command(
            self,
            cmd("TS.RANGE")
                .key(key)
                .arg(from_timestamp)
                .arg(to_timestamp)
                .arg(options),
        )
    }

    /// Query a range in reverse direction
    ///
    /// # Arguments
    /// * `key` - the key name for the time series.
    /// * `from_timestamp` - start timestamp for the range query (integer UNIX timestamp in milliseconds)
    ///   or `-`to denote the timestamp of the earliest sample in the time series.
    /// * `to_timestamp` - end timestamp for the range query (integer UNIX timestamp in milliseconds)
    ///   or `+` to denote the timestamp of the latest sample in the time series.
    /// * `options` - See [`TsRangeOptions`](TsRangeOptions)
    ///
    /// # Return
    /// A collection of keys
    ///
    /// # Notes
    /// * When the time series is a compaction,
    ///   the last compacted value may aggregate raw values with timestamp beyond `to_timestamp`.
    ///   That is because `to_timestamp` only limits the timestamp of the compacted value,
    ///   which is the start time of the raw bucket that was compacted.
    ///
    /// # See Also
    /// * [<https://redis.io/commands/ts.revrange/>](https://redis.io/commands/ts.revrange/)
    #[must_use]
    fn ts_revrange<R: Response>(
        self,
        key: impl Serialize,
        from_timestamp: impl Serialize,
        to_timestamp: impl Serialize,
        options: TsRangeOptions,
    ) -> PreparedCommand<'a, Self, R> {
        prepare_command(
            self,
            cmd("TS.REVRANGE")
                .key(key)
                .arg(from_timestamp)
                .arg(to_timestamp)
                .arg(options),
        )
    }
}

/// Options for the [`ts_add`](TimeSeriesCommands::ts_add) command.
///
/// # Notes
/// * You can use this command to add data to a nonexisting time series in a single command.
///   This is why [`retention`](TsAddOptions::retention), [`encoding`](TsAddOptions::encoding),
///   [`chunk_size`](TsAddOptions::chunk_size), [`on_duplicate`](TsAddOptions::on_duplicate),
///   and [`labels`](TsAddOptions::labels) are optional arguments.
/// * Setting [`retention`](TsAddOptions::retention) and [`labels`](TsAddOptions::labels) introduces additional time complexity.
#[derive(Default, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub struct TsAddOptions<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    retention: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    encoding: Option<TsEncoding>,
    #[serde(skip_serializing_if = "Option::is_none")]
    chunk_size: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    on_duplicate: Option<TsDuplicatePolicy>,
    #[serde(skip_serializing_if = "SmallVec::is_empty")]
    labels: SmallVec<[(&'a str, &'a str); 10]>,
}

impl<'a> TsAddOptions<'a> {
    /// maximum retention period, compared to the maximum existing timestamp, in milliseconds.
    ///
    /// Use it only if you are creating a new time series.
    /// It is ignored if you are adding samples to an existing time series.
    /// See [`retention`](TsCreateOptions::retention).
    #[must_use]
    pub fn retention(mut self, retention_period: u64) -> Self {
        self.retention = Some(retention_period);
        self
    }

    /// specifies the series sample's encoding format.
    ///
    /// Use it only if you are creating a new time series.
    /// It is ignored if you are adding samples to an existing time series.
    /// See [`encoding`](TsCreateOptions::encoding).
    #[must_use]
    pub fn encoding(mut self, encoding: TsEncoding) -> Self {
        self.encoding = Some(encoding);
        self
    }

    /// memory size, in bytes, allocated for each data chunk.
    ///
    /// Use it only if you are creating a new time series.
    /// It is ignored if you are adding samples to an existing time series.
    /// See [`chunk_size`](TsCreateOptions::chunk_size).
    #[must_use]
    pub fn chunk_size(mut self, chunk_size: u32) -> Self {
        self.chunk_size = Some(chunk_size);
        self
    }

    /// overwrite key and database configuration for
    /// [`DUPLICATE_POLICY`](https://redis.io/docs/stack/timeseries/configuration/#duplicate_policy)
    #[must_use]
    pub fn on_duplicate(mut self, policy: TsDuplicatePolicy) -> Self {
        self.on_duplicate = Some(policy);
        self
    }

    /// set of label-value pairs that represent metadata labels of the time series.
    ///
    /// Use it only if you are creating a new time series.
    /// It is ignored if you are adding samples to an existing time series.
    /// See [`labels`](TsCreateOptions::labels).
    ///
    /// The [`ts_mget`](TimeSeriesCommands::ts_mget), [`ts_mrange`](TimeSeriesCommands::ts_mrange),
    /// and [`ts_mrevrange`](TimeSeriesCommands::ts_mrevrange) commands operate on multiple time series based on their labels.
    /// The [`ts_queryindex`](TimeSeriesCommands::ts_queryindex) command returns all time series keys matching a given filter based on their labels.
    #[must_use]
    pub fn labels(mut self, labels: impl IntoIterator<Item = (&'a str, &'a str)>) -> Self {
        self.labels.extend(labels);
        self
    }
}

/// specifies the series samples encoding format.
///
/// `Compressed` is almost always the right choice.
/// Compression not only saves memory but usually improves performance due to a lower number of memory accesses.
/// It can result in about 90% memory reduction. The exception are highly irregular timestamps or values, which occur rarely.
///
/// When not specified, the option is set to `Compressed`.
#[derive(Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum TsEncoding {
    /// applies compression to the series samples.
    Compressed,
    /// keeps the raw samples in memory.
    ///
    /// Adding this flag keeps data in an uncompressed form.
    Uncompressed,
}

/// [`Policy`](https://redis.io/docs/stack/timeseries/configuration/#duplicate_policy)
/// for handling samples with identical timestamps
///
///  It is used with one of the following values:
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum TsDuplicatePolicy {
    /// ignore any newly reported value and reply with an error
    Block,
    /// ignore any newly reported value
    First,
    /// override with the newly reported value
    Last,
    /// only override if the value is lower than the existing value
    Min,
    /// only override if the value is higher than the existing value
    Max,
    /// If a previous sample exists, add the new sample to it so that the updated value is equal to (previous + new).     ///
    /// If no previous sample exists, set the updated value equal to the new value.
    Sum,
}

/// Options for the [`ts_add`](TimeSeriesCommands::ts_create) command.
#[derive(Default, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub struct TsCreateOptions<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    retention: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    encoding: Option<TsEncoding>,
    #[serde(skip_serializing_if = "Option::is_none")]
    chunk_size: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    duplicate_policy: Option<TsDuplicatePolicy>,
    #[serde(skip_serializing_if = "SmallVec::is_empty")]
    labels: SmallVec<[(&'a str, &'a str); 10]>,
}

impl<'a> TsCreateOptions<'a> {
    /// maximum age for samples compared to the highest reported timestamp, in milliseconds.
    ///
    /// Samples are expired based solely on the difference between their timestamp
    /// and the timestamps passed to subsequent [`ts_add`](TimeSeriesCommands::ts_add),
    /// [`ts_madd`](TimeSeriesCommands::ts_madd), [`ts_incrby`](TimeSeriesCommands::ts_incrby),
    /// and [`ts_decrby`](TimeSeriesCommands::ts_decrby) calls.
    ///
    /// When set to 0, samples never expire. When not specified, the option is set to the global
    /// [`RETENTION_POLICY`](https://redis.io/docs/stack/timeseries/configuration/#retention_policy)
    /// configuration of the database, which by default is 0.
    #[must_use]
    pub fn retention(mut self, retention_period: u64) -> Self {
        self.retention = Some(retention_period);
        self
    }

    /// specifies the series sample's encoding format.
    #[must_use]
    pub fn encoding(mut self, encoding: TsEncoding) -> Self {
        self.encoding = Some(encoding);
        self
    }

    /// initial allocation size, in bytes, for the data part of each new chunk. Actual chunks may consume more memory.
    ///
    /// Changing chunkSize (using [`ts_alter`](TimeSeriesCommands::ts_alter)) does not affect existing chunks.
    ///
    /// Must be a multiple of 8 in the range [48 .. 1048576].
    /// When not specified, it is set to 4096 bytes (a single memory page).
    ///
    /// Note: Before v1.6.10 no minimum was enforced. Between v1.6.10 and v1.6.17 and in v1.8.0 the minimum value was 128.
    /// Since v1.8.1 the minimum value is 48.
    ///
    /// The data in each key is stored in chunks. Each chunk contains header and data for a given timeframe.
    /// An index contains all chunks. Iterations occur inside each chunk. Depending on your use case, consider these tradeoffs for having smaller or larger sizes of chunks:
    /// * Insert performance: Smaller chunks result in slower inserts (more chunks need to be created).
    /// * Query performance: Queries for a small subset when the chunks are very large are slower,
    ///   as we need to iterate over the chunk to find the data.
    /// * Larger chunks may take more memory when you have a very large number of keys and very few samples per key,
    ///   or less memory when you have many samples per key.
    ///
    /// If you are unsure about your use case, select the default.
    #[must_use]
    pub fn chunk_size(mut self, chunk_size: u32) -> Self {
        self.chunk_size = Some(chunk_size);
        self
    }

    /// policy for handling insertion ([`ts_add`](TimeSeriesCommands::ts_add) and [`ts_madd`](TimeSeriesCommands::ts_madd))
    /// of multiple samples with identical timestamps
    #[must_use]
    pub fn duplicate_policy(mut self, policy: TsDuplicatePolicy) -> Self {
        self.duplicate_policy = Some(policy);
        self
    }

    /// set of label-value pairs that represent metadata labels of the time series.
    ///
    /// Use it only if you are creating a new time series.
    /// It is ignored if you are adding samples to an existing time series.
    /// See [`labels`](TsCreateOptions::labels).
    ///
    /// The [`ts_mget`](TimeSeriesCommands::ts_mget), [`ts_mrange`](TimeSeriesCommands::ts_mrange),
    /// and [`ts_mrevrange`](TimeSeriesCommands::ts_mrevrange) commands operate on multiple time series based on their labels.
    /// The [`ts_queryindex`](TimeSeriesCommands::ts_queryindex) command returns all time series keys matching a given filter based on their labels.
    #[must_use]
    pub fn labels(mut self, labels: impl IntoIterator<Item = (&'a str, &'a str)>) -> Self {
        self.labels.extend(labels);
        self
    }
}

/// Aggregation type for the [`ts_createrule`](TimeSeriesCommands::ts_createrule)
/// and [`ts_mrange`](TimeSeriesCommands::ts_mrange) commands.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum TsAggregationType {
    /// Arithmetic mean of all values
    Avg,
    /// Sum of all values
    Sum,
    /// Minimum value
    Min,
    /// Maximum value
    Max,
    /// Difference between the highest and the lowest value
    Range,
    /// Number of values
    Count,
    /// Value with lowest timestamp in the bucket
    First,
    /// Value with highest timestamp in the bucket
    Last,
    /// Population standard deviation of the values
    #[serde(rename = "STD.P")]
    StdP,
    /// Sample standard deviation of the values
    #[serde(rename = "STD.S")]
    StdS,
    /// Population variance of the values
    #[serde(rename = "VAR.P")]
    VarP,
    /// Sample variance of the values
    #[serde(rename = "VAR.S")]
    VarS,
    /// Time-weighted average over the bucket's timeframe (since RedisTimeSeries v1.8)
    Twa,
}

/// Options for the [`ts_createrule`](TimeSeriesCommands::ts_createrule) command.
#[derive(Default, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub struct TsCreateRuleOptions {
    #[serde(rename = "", skip_serializing_if = "Option::is_none")]
    align_timestamp: Option<u64>,
}

impl TsCreateRuleOptions {
    /// ensures that there is a bucket that starts exactly at `align_timestamp`
    /// and aligns all other buckets accordingly. (since RedisTimeSeries v1.8)
    ///
    /// It is expressed in milliseconds.
    /// The default value is 0 aligned with the epoch.
    /// For example, if `bucket_duration` is 24 hours (`24 * 3600 * 1000`), setting `align_timestamp`
    /// to 6 hours after the epoch (`6 * 3600 * 1000`) ensures that each bucket’s timeframe is `[06:00 .. 06:00)`.
    #[must_use]
    pub fn align_timestamp(mut self, align_timestamp: u64) -> Self {
        self.align_timestamp = Some(align_timestamp);
        self
    }
}

/// Options for the [`ts_incrby`](TimeSeriesCommands::ts_incrby)
/// and [`ts_decrby`](TimeSeriesCommands::ts_decrby) commands.
///
/// # Notes
/// * You can use this command to add data to a nonexisting time series in a single command.
///   This is why `retention`, `uncompressed`, `chunk_size`, and `labels` are optional arguments.
/// * When specified and the key doesn't exist, a new time series is created.
///   Setting the `retention` and `labels` options introduces additional time complexity.
#[derive(Default, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub struct TsIncrByDecrByOptions<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    timestamp: Option<TsTimestamp>,
    #[serde(skip_serializing_if = "Option::is_none")]
    retention: Option<u64>,
    #[serde(
        skip_serializing_if = "std::ops::Not::not",
        serialize_with = "serialize_flag"
    )]
    uncompressed: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    chunk_size: Option<u32>,
    #[serde(skip_serializing_if = "SmallVec::is_empty")]
    labels: SmallVec<[(&'a str, &'a str); 10]>,
}

impl<'a> TsIncrByDecrByOptions<'a> {
    /// is (integer) UNIX sample timestamp in milliseconds or * to set the timestamp according to the server clock.
    ///
    /// timestamp must be equal to or higher than the maximum existing timestamp.
    /// When equal, the value of the sample with the maximum existing timestamp is decreased.
    /// If it is higher, a new sample with a timestamp set to timestamp is created,
    /// and its value is set to the value of the sample with the maximum existing timestamp minus value.
    ///
    /// If the time series is empty, the value is set to value.
    ///
    /// When not specified, the timestamp is set according to the server clock.
    #[must_use]
    pub fn timestamp(mut self, timestamp: TsTimestamp) -> Self {
        self.timestamp = Some(timestamp);
        self
    }

    /// maximum age for samples compared to the highest reported timestamp, in milliseconds.
    ///
    /// Use it only if you are creating a new time series.
    /// It is ignored if you are adding samples to an existing time series
    ///
    /// See [`retention`](TsCreateOptions::retention).
    #[must_use]
    pub fn retention(mut self, retention_period: u64) -> Self {
        self.retention = Some(retention_period);
        self
    }

    /// changes data storage from compressed (default) to uncompressed.
    ///
    /// Use it only if you are creating a new time series.
    /// It is ignored if you are adding samples to an existing time series.
    /// See [`encoding`](TsCreateOptions::encoding).
    #[must_use]
    pub fn uncompressed(mut self) -> Self {
        self.uncompressed = true;
        self
    }

    /// memory size, in bytes, allocated for each data chunk.
    ///
    /// Use it only if you are creating a new time series.
    /// It is ignored if you are adding samples to an existing time series.
    /// See [`chunk_size`](TsCreateOptions::chunk_size).
    #[must_use]
    pub fn chunk_size(mut self, chunk_size: u32) -> Self {
        self.chunk_size = Some(chunk_size);
        self
    }

    /// set of label-value pairs that represent metadata labels of the time series.
    ///
    /// Use it only if you are creating a new time series.
    /// It is ignored if you are adding samples to an existing time series.
    /// See [`labels`](TsCreateOptions::labels).
    #[must_use]
    pub fn labels(mut self, label: &'a str, value: &'a str) -> Self {
        self.labels.push((label, value));
        self
    }
}

/// Options for the [`ts_get`](TimeSeriesCommands::ts_get) command.
#[derive(Default, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub struct TsGetOptions {
    #[serde(
        skip_serializing_if = "std::ops::Not::not",
        serialize_with = "serialize_flag"
    )]
    latest: bool,
}

impl TsGetOptions {
    /// Used when a time series is a compaction.
    ///
    /// With `latest`, [`ts_get`](TimeSeriesCommands::ts_get)
    /// also reports the compacted value of the latest possibly partial bucket,
    /// given that this bucket's start time falls within [`from_timestamp`, `to_timestamp`].
    /// Without `latest`, [`ts_get`](TimeSeriesCommands::ts_get)
    ///  does not report the latest possibly partial bucket.
    /// When a time series is not a compaction, `latest` is ignored.
    ///
    /// The data in the latest bucket of a compaction is possibly partial.
    /// A bucket is closed and compacted only upon arrival of a new sample that opens a new latest bucket.
    /// There are cases, however, when the compacted value of the latest possibly partial bucket is also required.
    /// In such a case, use `latest`.
    #[must_use]
    pub fn latest(mut self) -> Self {
        self.latest = true;
        self
    }
}

/// Result for the [`ts_info`](TimeSeriesCommands::ts_info) command.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TsInfoResult {
    /// key name
    pub key_self_name: String,
    /// Total number of samples in this time series
    pub total_samples: usize,
    /// Total number of bytes allocated for this time series, which is the sum of
    /// * The memory used for storing the series' configuration parameters (retention period, duplication policy, etc.)
    /// * The memory used for storing the series' compaction rules
    /// * The memory used for storing the series' labels (key-value pairs)
    /// * The memory used for storing the chunks (chunk header + compressed/uncompressed data)
    pub memory_usage: usize,
    ///First timestamp present in this time series
    pub first_timestamp: u64,
    /// Last timestamp present in this time series
    pub last_timestamp: u64,
    /// The retention period, in milliseconds, for this time series
    pub retention_time: u64,
    /// Number of chunks used for this time series
    pub chunk_count: usize,
    /// The initial allocation size, in bytes, for the data part of each new chunk.
    /// Actual chunks may consume more memory.
    /// Changing the chunk size (using [`ts_alter`](TimeSeriesCommands::ts_alter)) does not affect existing chunks.
    pub chunk_size: usize,
    /// The chunks type: `compressed` or `uncompressed`
    pub chunk_type: String,
    /// The [`duplicate policy`](https://redis.io/docs/stack/timeseries/configuration/#duplicate_policy) of this time series
    pub duplicate_policy: Option<TsDuplicatePolicy>,
    /// A map of label-value pairs that represent the metadata labels of this time series
    pub labels: HashMap<String, String>,
    /// Key name for source time series in case the current series is a target
    ///  of a [`compaction rule`](https://redis.io/commands/ts.createrule/)
    pub source_key: String,
    /// A nested array of the [`compaction rules`](https://redis.io/commands/ts.createrule/)
    /// defined in this time series, with these elements for each rule:
    /// * The compaction key
    /// * The bucket duration
    /// * The aggregator
    /// * The alignment (since RedisTimeSeries v1.8)
    #[serde(deserialize_with = "deserialize_compation_rules")]
    pub rules: Vec<TsCompactionRule>,
    /// Additional chunk information when the `debug` flag is specified in [`ts_info`](TimeSeriesCommands::ts_info)
    #[serde(rename = "Chunks")]
    pub chunks: Option<Vec<TsInfoChunkResult>>,
    /// Additional values for future versions of the command
    #[serde(flatten)]
    pub additional_values: HashMap<String, Value>,
}

/// Additional debug result for the [`ts_info`](TimeSeriesCommands::ts_info) command.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TsInfoChunkResult {
    /// First timestamp present in the chunk
    pub start_timestamp: i64,
    /// Last timestamp present in the chunk
    pub end_timestamp: i64,
    /// Total number of samples in the chunk
    pub samples: usize,
    /// The chunk data size in bytes.
    /// This is the exact size that used for data only inside the chunk.
    /// It does not include other overheads.
    pub size: usize,
    /// Ratio of `size` and `samples`
    pub bytes_per_sample: f64,
}

/// information about the [`compaction rules`](https://redis.io/commands/ts.createrule/)
/// of a time series collection, in the context of the [`ts_info`](TimeSeriesCommands::ts_info) command.
#[derive(Debug)]
pub struct TsCompactionRule {
    /// The compaction key
    pub compaction_key: String,
    /// The bucket duration
    pub bucket_duration: u64,
    /// The aggregator
    pub aggregator: TsAggregationType,
    /// The alignment (since RedisTimeSeries v1.8)
    pub alignment: u64,
}

fn deserialize_compation_rules<'de, D>(deserializer: D) -> Result<Vec<TsCompactionRule>, D::Error>
where
    D: de::Deserializer<'de>,
{
    struct Visitor;

    impl<'de> de::Visitor<'de> for Visitor {
        type Value = Vec<TsCompactionRule>;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            formatter.write_str("an array of TsCompactionRule")
        }

        fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
        where
            A: de::MapAccess<'de>,
        {
            let mut rules = Vec::with_capacity(map.size_hint().unwrap_or_default());
            while let Some(compaction_key) = map.next_key()? {
                let (bucket_duration, aggregator, alignment) =
                    map.next_value::<(u64, TsAggregationType, u64)>()?;
                rules.push(TsCompactionRule {
                    compaction_key,
                    bucket_duration,
                    aggregator,
                    alignment,
                });
            }

            Ok(rules)
        }
    }

    deserializer.deserialize_map(Visitor)
}

// impl<'de> de::Deserialize<'de> for Vec<TsCompactionRule> {
//     fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
//     where
//         D: de::Deserializer<'de> {
//         struct Visitor;

//         impl<'de> de::Visitor<'de> for Visitor {
//             type Value = TsCompactionRule;

//             fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
//                 formatter.write_str("TsCompactionRule")
//             }

//             fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
//                 where
//                     A: de::MapAccess<'de>, {
//                 let Some(entry)
//             }
//         }

//         deserializer.deserialize_map(Visitor)
//     }
// }

/// Options for the [`ts_mget`](TimeSeriesCommands::ts_mget) command.
#[derive(Default, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub struct TsMGetOptions<'a> {
    #[serde(
        skip_serializing_if = "std::ops::Not::not",
        serialize_with = "serialize_flag"
    )]
    latest: bool,
    #[serde(
        skip_serializing_if = "std::ops::Not::not",
        serialize_with = "serialize_flag"
    )]
    withlabels: bool,
    #[serde(skip_serializing_if = "SmallVec::is_empty")]
    selected_labels: SmallVec<[&'a str; 10]>,
}

impl<'a> TsMGetOptions<'a> {
    /// Used when a time series is a compaction.
    ///
    /// With `latest`, [`ts_mget`](TimeSeriesCommands::ts_mget)
    /// also reports the compacted value of the latest possibly partial bucket,
    /// given that this bucket's start time falls within [`from_timestamp`, `to_timestamp`].
    /// Without `latest`, [`ts_mget`](TimeSeriesCommands::ts_mget)
    ///  does not report the latest possibly partial bucket.
    /// When a time series is not a compaction, `latest` is ignored.
    ///
    /// The data in the latest bucket of a compaction is possibly partial.
    /// A bucket is closed and compacted only upon arrival of a new sample that opens a new latest bucket.
    /// There are cases, however, when the compacted value of the latest possibly partial bucket is also required.
    /// In such a case, use `latest`.
    #[must_use]
    pub fn latest(mut self) -> Self {
        self.latest = true;
        self
    }

    /// Includes in the reply all label-value pairs representing metadata labels of the time series.
    ///
    /// If `withlabels` or `selected_labels` are not specified, by default, an empty list is reported as label-value pairs.
    #[must_use]
    pub fn withlabels(mut self) -> Self {
        self.withlabels = true;
        self
    }

    /// returns a subset of the label-value pairs that represent metadata labels of the time series.
    ///
    /// Use when a large number of labels exists per series, but only the values of some of the labels are required.
    /// If `withlabels` or `selected_labels` are not specified, by default, an empty list is reported as label-value pairs.
    #[must_use]
    pub fn selected_label(mut self, label: &'a str) -> Self {
        self.selected_labels.push(label);
        self
    }
}

/// Result for the [`ts_mget`](TimeSeriesCommands::ts_mget) command.
#[derive(Debug, Deserialize)]
pub struct TsSample {
    /// Label-value pairs
    ///
    /// * By default, an empty list is reported
    /// * If [`withlabels`](TsMGetOptions::withlabels) is specified, all labels associated with this time series are reported
    /// * If [`selected_labels`](TsMGetOptions::selected_labels) is specified, the selected labels are reported
    pub labels: HashMap<String, String>,
    /// Timestamp-value pairs for all samples/aggregations matching the range
    pub timestamp_value: (u64, f64),
}

/// Options for the [`ts_mrange`](TimeSeriesCommands::ts_mrange) and
/// [`ts_mrevrange`](TimeSeriesCommands::ts_mrevrange) commands.
#[derive(Default, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub struct TsMRangeOptions<'a> {
    #[serde(
        skip_serializing_if = "std::ops::Not::not",
        serialize_with = "serialize_flag"
    )]
    latest: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    filter_by_ts: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    filter_by_value: Option<(f64, f64)>,
    #[serde(
        skip_serializing_if = "std::ops::Not::not",
        serialize_with = "serialize_flag"
    )]
    withlabels: bool,
    #[serde(skip_serializing_if = "SmallVec::is_empty")]
    selected_labels: SmallVec<[&'a str; 10]>,
    #[serde(skip_serializing_if = "Option::is_none")]
    count: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    align: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    aggregation: Option<(TsAggregationType, u64)>,
    #[serde(skip_serializing_if = "Option::is_none")]
    buckettimestamp: Option<u64>,
    #[serde(
        skip_serializing_if = "std::ops::Not::not",
        serialize_with = "serialize_flag"
    )]
    empty: bool,
}

impl<'a> TsMRangeOptions<'a> {
    /// Used when a time series is a compaction.
    ///
    /// With `latest`, [`ts_mrange`](TimeSeriesCommands::ts_mrange)
    /// also reports the compacted value of the latest possibly partial bucket,
    /// given that this bucket's start time falls within [`from_timestamp`, `to_timestamp`].
    /// Without `latest`, [`ts_mrange`](TimeSeriesCommands::ts_mrange)
    /// does not report the latest possibly partial bucket.
    /// When a time series is not a compaction, `latest` is ignored.
    ///
    /// The data in the latest bucket of a compaction is possibly partial.
    /// A bucket is closed and compacted only upon arrival of a new sample that opens a new latest bucket.
    /// There are cases, however, when the compacted value of the latest possibly partial bucket is also required.
    /// In such a case, use `latest`.
    #[must_use]
    pub fn latest(mut self) -> Self {
        self.latest = true;
        self
    }

    /// filters samples by a list of specific timestamps.
    ///
    /// A sample passes the filter if its exact timestamp is specified and falls within [`from_timestamp`, `to_timestamp`].
    #[must_use]
    pub fn filter_by_ts(mut self, ts: &'a str) -> Self {
        self.filter_by_ts = Some(ts);
        self
    }

    /// filters samples by minimum and maximum values.
    #[must_use]
    pub fn filter_by_value(mut self, min: f64, max: f64) -> Self {
        self.filter_by_value = Some((min, max));
        self
    }

    /// Includes in the reply all label-value pairs representing metadata labels of the time series.
    ///
    /// If `withlabels` or `selected_labels` are not specified, by default, an empty list is reported as label-value pairs.
    #[must_use]
    pub fn withlabels(mut self) -> Self {
        self.withlabels = true;
        self
    }

    /// returns a subset of the label-value pairs that represent metadata labels of the time series.
    ///
    /// Use when a large number of labels exists per series, but only the values of some of the labels are required.
    /// If `withlabels` or `selected_labels` are not specified, by default, an empty list is reported as label-value pairs.
    #[must_use]
    pub fn selected_label(mut self, label: &'a str) -> Self {
        self.selected_labels.push(label);
        self
    }

    /// limits the number of returned samples.
    #[must_use]
    pub fn count(mut self, count: u32) -> Self {
        self.count = Some(count);
        self
    }

    /// A time bucket alignment control for `aggregation`.
    ///
    /// It controls the time bucket timestamps by changing the reference timestamp on which a bucket is defined.
    ///
    /// Values include:
    /// * `start` or `-`: The reference timestamp will be the query start interval time (`from_timestamp`) which can't be `-`
    /// * `end` or `+`: The reference timestamp will be the query end interval time (`to_timestamp`) which can't be `+`
    /// * A specific timestamp: align the reference timestamp to a specific time
    ///
    /// # Note
    /// When not provided, alignment is set to 0.
    #[must_use]
    pub fn align(mut self, align: &'a str) -> Self {
        self.align = Some(align);
        self
    }

    /// Aggregates results into time buckets, where:
    /// * `aggregator` - takes a value of [`TsAggregationType`](TsAggregationType)
    /// * `bucket_duration` - is duration of each bucket, in milliseconds.
    ///
    /// Without `align`, bucket start times are multiples of `bucket_duration`.
    ///
    /// With `align`, bucket start times are multiples of `bucket_duration` with remainder `align` % `bucket_duration`.
    ///
    /// The first bucket start time is less than or equal to `from_timestamp`.
    #[must_use]
    pub fn aggregation(mut self, aggregator: TsAggregationType, bucket_duration: u64) -> Self {
        self.aggregation = Some((aggregator, bucket_duration));
        self
    }

    /// controls how bucket timestamps are reported.
    /// `bucket_timestamp` values include:
    /// * `-` or `low` - Timestamp reported for each bucket is the bucket's start time (default)
    /// * `+` or `high` - Timestamp reported for each bucket is the bucket's end time
    /// * `~` or `mid` - Timestamp reported for each bucket is the bucket's mid time (rounded down if not an integer)
    #[must_use]
    pub fn bucket_timestamp(mut self, bucket_timestamp: u64) -> Self {
        self.buckettimestamp = Some(bucket_timestamp);
        self
    }

    /// A flag, which, when specified, reports aggregations also for empty buckets.
    /// when `aggregator` values are:
    /// * `sum`, `count` - the value reported for each empty bucket is `0`
    /// * `last` - the value reported for each empty bucket is the value
    ///   of the last sample before the bucket's start.
    ///   `NaN` when no such sample.
    /// * `twa` - the value reported for each empty bucket is the average value
    ///   over the bucket's timeframe based on linear interpolation
    ///   of the last sample before the bucket's start and the first sample after the bucket's end.
    ///   `NaN` when no such samples.
    /// * `min`, `max`, `range`, `avg`, `first`, `std.p`, `std.s` - the value reported for each empty bucket is `NaN`
    ///
    /// Regardless of the values of `from_timestamp` and `to_timestamp`,
    /// no data is reported for buckets that end before the earliest sample or begin after the latest sample in the time series.
    #[must_use]
    pub fn empty(mut self) -> Self {
        self.empty = true;
        self
    }
}

/// Result for the [`ts_mrange`](TimeSeriesCommands::ts_mrange) and
/// [`ts_mrevrange`](TimeSeriesCommands::ts_mrevrange) commands.
#[derive(Debug)]
pub struct TsRangeSample {
    /// Label-value pairs
    ///
    /// * By default, an empty list is reported
    /// * If [`withlabels`](TsMGetOptions::withlabels) is specified, all labels associated with this time series are reported
    /// * If [`selected_labels`](TsMGetOptions::selected_labels) is specified, the selected labels are reported
    pub labels: Vec<(String, String)>,
    pub reducers: Vec<String>,
    pub sources: Vec<String>,
    pub aggregators: Vec<String>,
    /// Timestamp-value pairs for all samples/aggregations matching the range
    pub values: Vec<(u64, f64)>,
}

impl<'de> de::Deserialize<'de> for TsRangeSample {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: de::Deserializer<'de>,
    {
        enum TsRangeSampleField {
            Aggregators(Vec<String>),
            Reducers(Vec<String>),
            Sources(Vec<String>),
            Values(Vec<(u64, f64)>),
        }

        impl<'de> de::Deserialize<'de> for TsRangeSampleField {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where
                D: de::Deserializer<'de>,
            {
                struct Visitor;

                impl<'de> de::Visitor<'de> for Visitor {
                    type Value = TsRangeSampleField;

                    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                        formatter.write_str("TsRangeSampleField")
                    }

                    fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
                    where
                        A: de::SeqAccess<'de>,
                    {
                        Ok(TsRangeSampleField::Values(Vec::<(u64, f64)>::deserialize(
                            SeqAccessDeserializer::new(seq),
                        )?))
                    }

                    fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
                    where
                        A: de::MapAccess<'de>,
                    {
                        let (Some((field, value)), None) = (
                            map.next_entry::<&str, Vec<String>>()?,
                            map.next_entry::<&str, Vec<String>>()?,
                        ) else {
                            return Err(de::Error::invalid_length(0, &"1 in map"));
                        };

                        match field {
                            "reducers" => Ok(TsRangeSampleField::Reducers(value)),
                            "sources" => Ok(TsRangeSampleField::Sources(value)),
                            "aggregators" => Ok(TsRangeSampleField::Aggregators(value)),
                            _ => Err(de::Error::unknown_field(
                                field,
                                &["reducers", "sources", "aggregators"],
                            )),
                        }
                    }
                }

                deserializer.deserialize_any(Visitor)
            }
        }

        struct Visitor;

        impl<'de> de::Visitor<'de> for Visitor {
            type Value = TsRangeSample;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("TsRangeSample")
            }

            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
            where
                A: de::SeqAccess<'de>,
            {
                let mut sample = TsRangeSample {
                    labels: Vec::new(),
                    reducers: Vec::new(),
                    sources: Vec::new(),
                    aggregators: Vec::new(),
                    values: Vec::new(),
                };

                let Some(labels) = seq.next_element::<Vec<(String, String)>>()? else {
                    return Err(de::Error::invalid_length(0, &"more elements in sequence"));
                };

                sample.labels = labels;

                while let Some(field) = seq.next_element::<TsRangeSampleField>()? {
                    match field {
                        TsRangeSampleField::Aggregators(aggregators) => {
                            sample.aggregators = aggregators
                        }
                        TsRangeSampleField::Reducers(reducers) => sample.reducers = reducers,
                        TsRangeSampleField::Sources(sources) => sample.sources = sources,
                        TsRangeSampleField::Values(values) => sample.values = values,
                    }
                }

                Ok(sample)
            }
        }

        deserializer.deserialize_seq(Visitor)
    }
}

/// Options for the [`ts_mrange`](TimeSeriesCommands::ts_mrange) command.
#[derive(Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub struct TsGroupByOptions<'a> {
    groupby: &'a str,
    reduce: TsAggregationType,
}

impl<'a> TsGroupByOptions<'a> {
    /// aggregates results across different time series, grouped by the provided label name.
    ///
    /// When combined with [`aggregation`](TsMRangeOptions::aggregation) the groupby/reduce is applied post aggregation stage.
    ///
    /// # Arguments
    /// * `label` - is the label name to group a series by. A new series for each value is produced.
    /// * `reducer` - is the reducer type used to aggregate series that share the same label value.
    ///
    /// # Notes
    /// * The produced time series is named `<label>=<groupbyvalue>`
    /// * The produced time series contains two labels with these label array structures:
    ///   * `reducer`, the reducer used
    ///   * `source`, the time series keys used to compute the grouped series (key1,key2,key3,...)
    #[must_use]
    pub fn new(label: &'a str, reducer: TsAggregationType) -> Self {
        Self {
            groupby: label,
            reduce: reducer,
        }
    }
}

/// Options for the [`ts_range`](TimeSeriesCommands::ts_range) and
/// [`ts_revrange`](TimeSeriesCommands::ts_revrange) commands.
#[derive(Default, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub struct TsRangeOptions<'a> {
    #[serde(
        skip_serializing_if = "std::ops::Not::not",
        serialize_with = "serialize_flag"
    )]
    latest: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    filter_by_ts: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    filter_by_value: Option<(f64, f64)>,
    #[serde(skip_serializing_if = "Option::is_none")]
    count: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    align: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    aggregation: Option<(TsAggregationType, u64)>,
    #[serde(skip_serializing_if = "Option::is_none")]
    buckettimestamp: Option<u64>,
    #[serde(
        skip_serializing_if = "std::ops::Not::not",
        serialize_with = "serialize_flag"
    )]
    empty: bool,
}

impl<'a> TsRangeOptions<'a> {
    /// Used when a time series is a compaction.
    ///
    /// With `latest`, [`ts_range`](TimeSeriesCommands::ts_range)
    /// also reports the compacted value of the latest possibly partial bucket,
    /// given that this bucket's start time falls within [`from_timestamp`, `to_timestamp`].
    /// Without `latest`, [`ts_range`](TimeSeriesCommands::ts_range)
    /// does not report the latest possibly partial bucket.
    /// When a time series is not a compaction, `latest` is ignored.
    ///
    /// The data in the latest bucket of a compaction is possibly partial.
    /// A bucket is closed and compacted only upon arrival of a new sample that opens a new latest bucket.
    /// There are cases, however, when the compacted value of the latest possibly partial bucket is also required.
    /// In such a case, use `latest`.
    #[must_use]
    pub fn latest(mut self) -> Self {
        self.latest = true;
        self
    }

    /// filters samples by a list of specific timestamps.
    ///
    /// A sample passes the filter if its exact timestamp is specified and falls within [`from_timestamp`, `to_timestamp`].
    #[must_use]
    pub fn filter_by_ts(mut self, ts: &'a str) -> Self {
        self.filter_by_ts = Some(ts);
        self
    }

    /// filters samples by minimum and maximum values.
    #[must_use]
    pub fn filter_by_value(mut self, min: f64, max: f64) -> Self {
        self.filter_by_value = Some((min, max));
        self
    }

    /// limits the number of returned samples.
    #[must_use]
    pub fn count(mut self, count: u32) -> Self {
        self.count = Some(count);
        self
    }

    /// A time bucket alignment control for `aggregation`.
    ///
    /// It controls the time bucket timestamps by changing the reference timestamp on which a bucket is defined.
    ///
    /// Values include:
    /// * `start` or `-`: The reference timestamp will be the query start interval time (`from_timestamp`) which can't be `-`
    /// * `end` or `+`: The reference timestamp will be the query end interval time (`to_timestamp`) which can't be `+`
    /// * A specific timestamp: align the reference timestamp to a specific time
    ///
    /// # Note
    /// When not provided, alignment is set to 0.
    #[must_use]
    pub fn align(mut self, align: &'a str) -> Self {
        self.align = Some(align);
        self
    }

    /// Aggregates results into time buckets, where:
    /// * `aggregator` - takes a value of [`TsAggregationType`](TsAggregationType)
    /// * `bucket_duration` - is duration of each bucket, in milliseconds.
    ///
    /// Without `align`, bucket start times are multiples of `bucket_duration`.
    ///
    /// With `align`, bucket start times are multiples of `bucket_duration` with remainder `align` % `bucket_duration`.
    ///
    /// The first bucket start time is less than or equal to `from_timestamp`.
    #[must_use]
    pub fn aggregation(mut self, aggregator: TsAggregationType, bucket_duration: u64) -> Self {
        self.aggregation = Some((aggregator, bucket_duration));
        self
    }

    /// controls how bucket timestamps are reported.
    /// `bucket_timestamp` values include:
    /// * `-` or `low` - Timestamp reported for each bucket is the bucket's start time (default)
    /// * `+` or `high` - Timestamp reported for each bucket is the bucket's end time
    /// * `~` or `mid` - Timestamp reported for each bucket is the bucket's mid time (rounded down if not an integer)
    #[must_use]
    pub fn bucket_timestamp(mut self, bucket_timestamp: u64) -> Self {
        self.buckettimestamp = Some(bucket_timestamp);
        self
    }

    /// A flag, which, when specified, reports aggregations also for empty buckets.
    /// when `aggregator` values are:
    /// * `sum`, `count` - the value reported for each empty bucket is `0`
    /// * `last` - the value reported for each empty bucket is the value
    ///   of the last sample before the bucket's start.
    ///   `NaN` when no such sample.
    /// * `twa` - the value reported for each empty bucket is the average value
    ///   over the bucket's timeframe based on linear interpolation
    ///   of the last sample before the bucket's start and the first sample after the bucket's end.
    ///   `NaN` when no such samples.
    /// * `min`, `max`, `range`, `avg`, `first`, `std.p`, `std.s` - the value reported for each empty bucket is `NaN`
    ///
    /// Regardless of the values of `from_timestamp` and `to_timestamp`,
    /// no data is reported for buckets that end before the earliest sample or begin after the latest sample in the time series.
    #[must_use]
    pub fn empty(mut self) -> Self {
        self.empty = true;
        self
    }
}

/// Timeseries Timestamp
pub enum TsTimestamp {
    /// User specified timestamp
    Value(u64),
    /// Unix time of the server clock (*)
    ServerClock,
}

impl Serialize for TsTimestamp {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            TsTimestamp::Value(ts) => serializer.serialize_u64(*ts),
            TsTimestamp::ServerClock => serializer.serialize_str("*"),
        }
    }
}