redis-cloud 0.9.5

Redis Cloud REST API client library
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
//! Database management operations for Essentials (Fixed) subscriptions
//!
//! This module provides database management functionality for Redis Cloud Essentials
//! (formerly Fixed) subscriptions, which offer a simplified, cost-effective option
//! for smaller workloads with predictable capacity requirements.
//!
//! # Overview
//!
//! Essentials databases are pre-configured Redis instances with fixed memory allocations
//! and simplified pricing. They're ideal for development, testing, and production
//! workloads that don't require auto-scaling or advanced clustering features.
//!
//! # Key Features
//!
//! - **Fixed Capacity**: Pre-defined memory sizes from 250MB to 12GB
//! - **Simple Pricing**: Predictable monthly costs
//! - **Essential Features**: Replication, persistence, and backup support
//! - **Module Support**: Limited module availability based on plan
//! - **Quick Setup**: Simplified configuration for faster deployment
//!
//! # Differences from Pro Databases
//!
//! - Fixed memory allocations (no auto-scaling)
//! - Limited to single-region deployments
//! - Simplified module selection
//! - No clustering support
//! - Predictable pricing model
//!
//! # Example Usage
//!
//! ```no_run
//! use redis_cloud::{CloudClient, FixedDatabaseHandler};
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let client = CloudClient::builder()
//!     .api_key("your-api-key")
//!     .api_secret("your-api-secret")
//!     .build()?;
//!
//! let handler = FixedDatabaseHandler::new(client);
//!
//! // Example: List databases in a fixed subscription (ID 123)
//! let databases = handler.list(123, None, None).await?;
//! # Ok(())
//! # }
//! ```

use crate::types::{Link, ProcessorResponse};
use crate::{CloudClient, Result};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use typed_builder::TypedBuilder;

// ============================================================================
// Models
// ============================================================================

/// `RedisLabs` Account Subscription Databases information
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AccountFixedSubscriptionDatabases {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub account_id: Option<i32>,

    /// HATEOAS links
    #[serde(skip_serializing_if = "Option::is_none")]
    pub links: Option<Vec<Link>>,
}

/// Database import request
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FixedDatabaseImportRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subscription_id: Option<i32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub database_id: Option<i32>,

    /// Type of storage from which to import the database RDB file or Redis data.
    pub source_type: String,

    /// One or more paths to source data files or Redis databases, as appropriate to specified source type.
    pub import_from_uri: Vec<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub command_type: Option<String>,
}

/// Database tag update request message
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DatabaseTagUpdateRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subscription_id: Option<i32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub database_id: Option<i32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub key: Option<String>,

    /// Database tag value
    pub value: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub command_type: Option<String>,
}

/// `DynamicEndpoints`
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DynamicEndpoints {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub public: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub private: Option<String>,
}

/// Database tag
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Tag {
    /// Database tag key.
    pub key: String,

    /// Database tag value.
    pub value: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub command_type: Option<String>,
}

/// Database tags update request message
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DatabaseTagsUpdateRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subscription_id: Option<i32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub database_id: Option<i32>,

    /// List of database tags.
    pub tags: Vec<Tag>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub command_type: Option<String>,
}

/// Optional. This database will be a replica of the specified Redis databases, provided as a list of objects with endpoint and certificate details.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DatabaseSyncSourceSpec {
    /// Redis URI of a source database. Example format: 'redis://user:password@host:port'. If the URI provided is a Redis Cloud database, only host and port should be provided. Example: '<redis://endpoint1:6379>'.
    pub endpoint: String,

    /// Defines if encryption should be used to connect to the sync source. If not set the source is a Redis Cloud database, it will automatically detect if the source uses encryption.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub encryption: Option<bool>,

    /// TLS/SSL certificate chain of the sync source. If not set and the source is a Redis Cloud database, it will automatically detect the certificate to use.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub server_cert: Option<String>,
}

/// Optional. A list of client TLS/SSL certificates. If specified, mTLS authentication will be required to authenticate user connections. If set to an empty list, TLS client certificates will be removed and mTLS will not be required. TLS connection may still apply, depending on the value of 'enableTls'.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DatabaseCertificateSpec {
    /// Client certificate public key in PEM format, with new line characters replaced with '\n'.
    pub public_certificate_pem_string: String,
}

/// Database tag
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CloudTag {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub key: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub value: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_at: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub updated_at: Option<String>,

    /// HATEOAS links
    #[serde(skip_serializing_if = "Option::is_none")]
    pub links: Option<Vec<Link>>,
}

/// Database slowlog entry
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DatabaseSlowLogEntry {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<i32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_time: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub duration: Option<i32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub arguments: Option<String>,
}

/// Database tag
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DatabaseTagCreateRequest {
    /// Database tag key.
    pub key: String,

    /// Database tag value.
    pub value: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub subscription_id: Option<i32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub database_id: Option<i32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub command_type: Option<String>,
}

/// Essentials database backup request message
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FixedDatabaseBackupRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subscription_id: Option<i32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub database_id: Option<i32>,

    /// Optional. Manually backs up data to this location, instead of the set 'periodicBackupPath' location.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub adhoc_backup_path: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub command_type: Option<String>,
}

/// Optional. Redis advanced capabilities (also known as modules) to be provisioned in the database. Use GET /database-modules to get a list of available advanced capabilities.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DatabaseModuleSpec {
    /// Redis advanced capability name. Use GET /database-modules for a list of available capabilities.
    pub name: String,

    /// Optional. Redis advanced capability parameters. Use GET /database-modules to get the available capabilities and their parameters.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parameters: Option<HashMap<String, Value>>,
}

/// Optional. Changes Replica Of (also known as Active-Passive) configuration details.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ReplicaOfSpec {
    /// Description of the replica configuration
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Optional. This database will be a replica of the specified Redis databases, provided as a list of objects with endpoint and certificate details.
    #[serde(default)]
    pub sync_sources: Vec<DatabaseSyncSourceSpec>,
}

/// Database backup status and configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DatabaseBackupStatus {
    /// Whether backup is enabled
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enabled: Option<bool>,

    /// Current backup status
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,

    /// Backup interval (e.g., "every-24-hours")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub interval: Option<String>,

    /// Backup destination path
    #[serde(skip_serializing_if = "Option::is_none")]
    pub destination: Option<String>,
}

/// Optional. Changes Redis database alert details.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DatabaseAlertSpec {
    /// Alert type. Available options depend on Plan type. See [Configure alerts](https://redis.io/docs/latest/operate/rc/databases/monitor-performance/#configure-metric-alerts) for more information.
    pub name: String,

    /// Value over which an alert will be sent. Default values and range depend on the alert type. See [Configure alerts](https://redis.io/docs/latest/operate/rc/databases/monitor-performance/#configure-metric-alerts) for more information.
    pub value: i32,
}

/// Redis list of database tags
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CloudTags {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub account_id: Option<i32>,

    /// HATEOAS links
    #[serde(skip_serializing_if = "Option::is_none")]
    pub links: Option<Vec<Link>>,
}

/// `FixedDatabase`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FixedDatabase {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub database_id: Option<i32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub protocol: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub provider: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub region: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub redis_version: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub redis_version_compliance: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub resp_version: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub plan_memory_limit: Option<f64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub plan_dataset_size: Option<f64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub memory_limit_measurement_unit: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub memory_limit_in_gb: Option<f64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub dataset_size_in_gb: Option<f64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub memory_used_in_mb: Option<f64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub network_monthly_usage_in_byte: Option<f64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub memory_storage: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub redis_flex: Option<bool>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub support_oss_cluster_api: Option<bool>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub use_external_endpoint_for_oss_cluster_api: Option<bool>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub data_persistence: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub replication: Option<bool>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub data_eviction_policy: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub activated_on: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_modified: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub public_endpoint: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub private_endpoint: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub dynamic_endpoints: Option<DynamicEndpoints>,

    /// Whether default Redis user is enabled
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enable_default_user: Option<bool>,

    /// Whether TLS is enabled for connections
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enable_tls: Option<bool>,

    /// Database password (masked in responses)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub password: Option<String>,

    /// List of source IP addresses or subnet masks allowed to connect
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source_ips: Option<Vec<String>>,

    /// Whether SSL client authentication is enabled
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ssl_client_authentication: Option<bool>,

    /// Whether TLS client authentication is enabled
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tls_client_authentication: Option<bool>,

    /// Replica of configuration
    #[serde(skip_serializing_if = "Option::is_none")]
    pub replica: Option<ReplicaOfSpec>,

    /// Whether database clustering is enabled
    #[serde(skip_serializing_if = "Option::is_none")]
    pub clustering_enabled: Option<bool>,

    /// Regex rules for custom hashing policy
    #[serde(skip_serializing_if = "Option::is_none")]
    pub regex_rules: Option<Vec<String>>,

    /// Hashing policy for clustering
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hashing_policy: Option<String>,

    /// Redis modules/capabilities enabled on this database
    #[serde(skip_serializing_if = "Option::is_none")]
    pub modules: Option<Vec<DatabaseModuleSpec>>,

    /// Database alert configurations
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alerts: Option<Vec<DatabaseAlertSpec>>,

    /// Backup configuration and status
    #[serde(skip_serializing_if = "Option::is_none")]
    pub backup: Option<DatabaseBackupStatus>,

    /// HATEOAS links
    #[serde(skip_serializing_if = "Option::is_none")]
    pub links: Option<Vec<Link>>,
}

/// `DatabaseSlowLogEntries`
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DatabaseSlowLogEntries {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub entries: Option<Vec<DatabaseSlowLogEntry>>,

    /// HATEOAS links
    #[serde(skip_serializing_if = "Option::is_none")]
    pub links: Option<Vec<Link>>,
}

/// `TaskStateUpdate`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TaskStateUpdate {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub task_id: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub command_type: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub timestamp: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub response: Option<ProcessorResponse>,

    /// HATEOAS links
    #[serde(skip_serializing_if = "Option::is_none")]
    pub links: Option<Vec<Link>>,
}

/// Essentials database definition
///
/// # Example
///
/// ```
/// use redis_cloud::fixed::databases::FixedDatabaseCreateRequest;
///
/// let request = FixedDatabaseCreateRequest::builder()
///     .name("my-database")
///     .replication(true)
///     .build();
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, TypedBuilder)]
#[serde(rename_all = "camelCase")]
pub struct FixedDatabaseCreateRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub subscription_id: Option<i32>,

    /// Name of the database. Database name is limited to 40 characters or less and must include only letters, digits, and hyphens ('-'). It must start with a letter and end with a letter or digit.
    #[builder(setter(into))]
    pub name: String,

    /// Optional. Database protocol. Use 'stack' to get all of Redis' advanced capabilities. Only use 'redis' for Pay-as-you-go or Redis Flex subscriptions. Default: 'stack' for most subscriptions, 'redis' for Redis Flex subscriptions.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub protocol: Option<String>,

    /// (Pay-as-you-go subscriptions only) Optional. Total memory in GB, including replication and other overhead. You cannot set both datasetSizeInGb and totalMemoryInGb.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub memory_limit_in_gb: Option<f64>,

    /// (Pay-as-you-go subscriptions only) Optional. The maximum amount of data in the dataset for this database in GB. You cannot set both datasetSizeInGb and totalMemoryInGb. If 'replication' is 'true', the database's total memory will be twice as large as the datasetSizeInGb. If 'replication' is false, the database's total memory will be the datasetSizeInGb value.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub dataset_size_in_gb: Option<f64>,

    /// (Pay-as-you-go subscriptions only) Optional. Support Redis [OSS Cluster API](https://redis.io/docs/latest/operate/rc/databases/configuration/clustering/#oss-cluster-api). Default: 'false'
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub support_oss_cluster_api: Option<bool>,

    /// Optional. If specified, redisVersion defines the Redis database version. If omitted, the Redis version will be set to the default version.  (available in 'GET /fixed/redis-versions')
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub redis_version: Option<String>,

    /// Optional. Redis Serialization Protocol version. Must be compatible with Redis version.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub resp_version: Option<String>,

    /// (Pay-as-you-go subscriptions only) Optional. If set to 'true', the database will use the external endpoint for OSS Cluster API. This setting blocks the database's private endpoint. Can only be set if 'supportOSSClusterAPI' is 'true'. Default: 'false'
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub use_external_endpoint_for_oss_cluster_api: Option<bool>,

    /// (Pay-as-you-go subscriptions only) Optional. Distributes database data to different cloud instances. Default: 'false'
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub enable_database_clustering: Option<bool>,

    /// (Pay-as-you-go subscriptions only) Optional. Specifies the number of master shards.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub number_of_shards: Option<i32>,

    /// Optional. Type and rate of data persistence in persistent storage. Use GET /fixed/plans/{planId} to see if your plan supports data persistence.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub data_persistence: Option<String>,

    /// Optional. Data eviction policy.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub data_eviction_policy: Option<String>,

    /// Optional. Sets database replication. Use GET /fixed/plans/{planId} to see if your plan supports database replication.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub replication: Option<bool>,

    /// Optional. The path to a backup storage location. If specified, the database will back up every 24 hours to this location, and you can manually back up the database to this location at any time. Use GET /fixed/plans/{planId} to see if your plan supports database backups.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub periodic_backup_path: Option<String>,

    /// Optional. List of source IP addresses or subnet masks to allow. If specified, Redis clients will be able to connect to this database only from within the specified source IP addresses ranges. Use GET /fixed/plans/{planId} to see how many CIDR allow rules your plan supports. Example: '['192.168.10.0/32', '192.168.12.0/24']'
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub source_ips: Option<Vec<String>>,

    /// (Pay-as-you-go subscriptions only) Optional. Hashing policy Regex rules. Used only if 'enableDatabaseClustering' is set to 'true' and .
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub regex_rules: Option<Vec<String>>,

    /// Optional. This database will be a replica of the specified Redis databases provided as one or more URI(s). Example: 'redis://user:password@host:port'. If the URI provided is a Redis Cloud database, only host and port should be provided. Example: ['<redis://endpoint1:6379>', '<redis://endpoint2:6380>'].
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub replica_of: Option<Vec<String>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub replica: Option<ReplicaOfSpec>,

    /// Optional. A public key client TLS/SSL certificate with new line characters replaced with '\n'. If specified, mTLS authentication will be required to authenticate user connections. Default: 'null'
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub client_ssl_certificate: Option<String>,

    /// Optional. A list of client TLS/SSL certificates. If specified, mTLS authentication will be required to authenticate user connections.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub client_tls_certificates: Option<Vec<DatabaseCertificateSpec>>,

    /// Optional. When 'true', requires TLS authentication for all connections - mTLS with valid clientTlsCertificates, regular TLS when clientTlsCertificates is not provided. Default: 'false'
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub enable_tls: Option<bool>,

    /// Optional. Password to access the database. If not set, a random 32-character alphanumeric password will be automatically generated.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub password: Option<String>,

    /// Optional. Redis database alert details.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub alerts: Option<Vec<DatabaseAlertSpec>>,

    /// Optional. Redis advanced capabilities (also known as modules) to be provisioned in the database. Use GET /database-modules to get a list of available advanced capabilities. Can only be set if 'protocol' is 'redis'.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub modules: Option<Vec<DatabaseModuleSpec>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub command_type: Option<String>,
}

/// Essentials database update request
///
/// # Example
///
/// ```
/// use redis_cloud::fixed::databases::FixedDatabaseUpdateRequest;
///
/// let request = FixedDatabaseUpdateRequest::builder()
///     .name("updated-name")
///     .build();
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, TypedBuilder)]
#[serde(rename_all = "camelCase")]
pub struct FixedDatabaseUpdateRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub subscription_id: Option<i32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub database_id: Option<i32>,

    /// Optional. Updated database name.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub name: Option<String>,

    /// (Pay-as-you-go subscriptions only) Optional. Total memory in GB, including replication and other overhead. You cannot set both datasetSizeInGb and totalMemoryInGb.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub memory_limit_in_gb: Option<f64>,

    /// (Pay-as-you-go subscriptions only) Optional. The maximum amount of data in the dataset for this database in GB. You cannot set both datasetSizeInGb and totalMemoryInGb. If 'replication' is 'true', the database's total memory will be twice as large as the datasetSizeInGb. If 'replication' is false, the database's total memory will be the datasetSizeInGb value.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub dataset_size_in_gb: Option<f64>,

    /// (Pay-as-you-go subscriptions only) Optional. Support Redis [OSS Cluster API](https://redis.io/docs/latest/operate/rc/databases/configuration/clustering/#oss-cluster-api).
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub support_oss_cluster_api: Option<bool>,

    /// Optional. Redis Serialization Protocol version. Must be compatible with Redis version.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub resp_version: Option<String>,

    /// (Pay-as-you-go subscriptions only) Optional. If set to 'true', the database will use the external endpoint for OSS Cluster API. This setting blocks the database's private endpoint. Can only be set if 'supportOSSClusterAPI' is 'true'. Default: 'false'
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub use_external_endpoint_for_oss_cluster_api: Option<bool>,

    /// (Pay-as-you-go subscriptions only) Optional. Distributes database data to different cloud instances.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub enable_database_clustering: Option<bool>,

    /// (Pay-as-you-go subscriptions only) Optional. Changes the number of master shards.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub number_of_shards: Option<i32>,

    /// Optional. Type and rate of data persistence in persistent storage. Use GET /fixed/plans/{planId} to see if your plan supports data persistence.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub data_persistence: Option<String>,

    /// Optional. Turns database replication on or off.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub data_eviction_policy: Option<String>,

    /// Optional. Sets database replication. Use GET /fixed/plans/{planId} to see if your plan supports database replication.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub replication: Option<bool>,

    /// Optional. Changes the backup location path. If specified, the database will back up every 24 hours to this location, and you can manually back up the database to this location at any time. Use GET /fixed/plans/{planId} to see if your plan supports database backups. If set to an empty string, the backup path will be removed.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub periodic_backup_path: Option<String>,

    /// Optional. List of source IP addresses or subnet masks to allow. If specified, Redis clients will be able to connect to this database only from within the specified source IP addresses ranges. Example: '['192.168.10.0/32', '192.168.12.0/24']'
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub source_ips: Option<Vec<String>>,

    /// Optional. This database will be a replica of the specified Redis databases provided as one or more URI (sample format: 'redis://user:password@host:port)'. If the URI provided is Redis Cloud instance, only host and port should be provided (using the format: ['<redis://endpoint1:6379>', '<redis://endpoint2:6380>'] ).
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub replica_of: Option<Vec<String>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub replica: Option<ReplicaOfSpec>,

    /// (Pay-as-you-go subscriptions only) Optional. Hashing policy Regex rules. Used only if 'shardingType' is 'custom-regex-rules'.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub regex_rules: Option<Vec<String>>,

    /// Optional. A public key client TLS/SSL certificate with new line characters replaced with '\n'. If specified, mTLS authentication will be required to authenticate user connections if it is not already required. If set to an empty string, TLS client certificates will be removed and mTLS will not be required. TLS connection may still apply, depending on the value of 'enableTls'.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub client_ssl_certificate: Option<String>,

    /// Optional. A list of client TLS/SSL certificates. If specified, mTLS authentication will be required to authenticate user connections. If set to an empty list, TLS client certificates will be removed and mTLS will not be required. TLS connection may still apply, depending on the value of 'enableTls'.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub client_tls_certificates: Option<Vec<DatabaseCertificateSpec>>,

    /// Optional. When 'true', requires TLS authentication for all connections - mTLS with valid clientTlsCertificates, regular TLS when clientTlsCertificates is not provided. If enableTls is set to 'false' while mTLS is required, it will remove the mTLS requirement and erase previously provided clientTlsCertificates.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub enable_tls: Option<bool>,

    /// Optional. Changes the password used to access the database with the 'default' user.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub password: Option<String>,

    /// Optional. When 'true', allows connecting to the database with the 'default' user. When 'false', only defined access control users can connect to the database.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub enable_default_user: Option<bool>,

    /// Optional. Changes Redis database alert details.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub alerts: Option<Vec<DatabaseAlertSpec>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option, into))]
    pub command_type: Option<String>,
}

// ============================================================================
// Handler
// ============================================================================

/// Handler for Essentials database operations
///
/// Manages fixed-capacity databases with simplified configuration
/// and predictable pricing for Redis Cloud Essentials subscriptions.
pub struct FixedDatabaseHandler {
    client: CloudClient,
}

impl FixedDatabaseHandler {
    /// Create a new handler
    #[must_use]
    pub fn new(client: CloudClient) -> Self {
        Self { client }
    }

    /// Get all databases in an Essentials subscription
    /// Gets a list of all databases in the specified Essentials subscription.
    ///
    /// GET /fixed/subscriptions/{subscriptionId}/databases
    pub async fn list(
        &self,
        subscription_id: i32,
        offset: Option<i32>,
        limit: Option<i32>,
    ) -> Result<AccountFixedSubscriptionDatabases> {
        let mut query = Vec::new();
        if let Some(v) = offset {
            query.push(format!("offset={v}"));
        }
        if let Some(v) = limit {
            query.push(format!("limit={v}"));
        }
        let query_string = if query.is_empty() {
            String::new()
        } else {
            format!("?{}", query.join("&"))
        };
        self.client
            .get(&format!(
                "/fixed/subscriptions/{subscription_id}/databases{query_string}"
            ))
            .await
    }

    /// Create Essentials database
    /// Creates a new database in the specified Essentials subscription.
    ///
    /// POST /fixed/subscriptions/{subscriptionId}/databases
    pub async fn create(
        &self,
        subscription_id: i32,
        request: &FixedDatabaseCreateRequest,
    ) -> Result<TaskStateUpdate> {
        self.client
            .post(
                &format!("/fixed/subscriptions/{subscription_id}/databases"),
                request,
            )
            .await
    }

    /// Delete Essentials database
    /// Deletes a database from an Essentials subscription.
    ///
    /// DELETE /fixed/subscriptions/{subscriptionId}/databases/{databaseId}
    pub async fn delete_by_id(
        &self,
        subscription_id: i32,
        database_id: i32,
    ) -> Result<TaskStateUpdate> {
        let response = self
            .client
            .delete_raw(&format!(
                "/fixed/subscriptions/{subscription_id}/databases/{database_id}"
            ))
            .await?;
        serde_json::from_value(response).map_err(Into::into)
    }

    /// Get a single Essentials database
    /// Gets details and settings of a single database in an Essentials subscription.
    ///
    /// GET /fixed/subscriptions/{subscriptionId}/databases/{databaseId}
    pub async fn get_by_id(&self, subscription_id: i32, database_id: i32) -> Result<FixedDatabase> {
        self.client
            .get(&format!(
                "/fixed/subscriptions/{subscription_id}/databases/{database_id}"
            ))
            .await
    }

    /// Update Essentials database
    /// Updates the specified Essentials database.
    ///
    /// PUT /fixed/subscriptions/{subscriptionId}/databases/{databaseId}
    pub async fn update(
        &self,
        subscription_id: i32,
        database_id: i32,
        request: &FixedDatabaseUpdateRequest,
    ) -> Result<TaskStateUpdate> {
        self.client
            .put(
                &format!("/fixed/subscriptions/{subscription_id}/databases/{database_id}"),
                request,
            )
            .await
    }

    /// Backup Essentials database status
    /// Information on the latest database backup status identified by Essentials subscription Id and Essentials database Id
    ///
    /// GET /fixed/subscriptions/{subscriptionId}/databases/{databaseId}/backup
    pub async fn get_backup_status(
        &self,
        subscription_id: i32,
        database_id: i32,
    ) -> Result<TaskStateUpdate> {
        self.client
            .get(&format!(
                "/fixed/subscriptions/{subscription_id}/databases/{database_id}/backup"
            ))
            .await
    }

    /// Back up Essentials database
    /// Manually back up the specified Essentials database to a backup path. By default, backups will be stored in the 'periodicBackupPath' location for this database.
    ///
    /// POST /fixed/subscriptions/{subscriptionId}/databases/{databaseId}/backup
    pub async fn backup(
        &self,
        subscription_id: i32,
        database_id: i32,
        request: &FixedDatabaseBackupRequest,
    ) -> Result<TaskStateUpdate> {
        self.client
            .post(
                &format!("/fixed/subscriptions/{subscription_id}/databases/{database_id}/backup"),
                request,
            )
            .await
    }

    /// Get Essentials database import status
    /// Gets information on the latest import attempt for this Essentials database.
    ///
    /// GET /fixed/subscriptions/{subscriptionId}/databases/{databaseId}/import
    pub async fn get_import_status(
        &self,
        subscription_id: i32,
        database_id: i32,
    ) -> Result<TaskStateUpdate> {
        self.client
            .get(&format!(
                "/fixed/subscriptions/{subscription_id}/databases/{database_id}/import"
            ))
            .await
    }

    /// Import data to an Essentials database
    /// Imports data from an RDB file or from a different Redis database into this Essentials database. WARNING: Importing data into a database removes all existing data from the database.
    ///
    /// POST /fixed/subscriptions/{subscriptionId}/databases/{databaseId}/import
    pub async fn import(
        &self,
        subscription_id: i32,
        database_id: i32,
        request: &FixedDatabaseImportRequest,
    ) -> Result<TaskStateUpdate> {
        self.client
            .post(
                &format!("/fixed/subscriptions/{subscription_id}/databases/{database_id}/import"),
                request,
            )
            .await
    }

    /// Get Essentials database slow-log by database id
    /// Get slow-log for a specific database identified by Essentials subscription Id and database Id
    ///
    /// GET /fixed/subscriptions/{subscriptionId}/databases/{databaseId}/slow-log
    pub async fn get_slow_log(
        &self,
        subscription_id: i32,
        database_id: i32,
    ) -> Result<DatabaseSlowLogEntries> {
        self.client
            .get(&format!(
                "/fixed/subscriptions/{subscription_id}/databases/{database_id}/slow-log"
            ))
            .await
    }

    /// Get database tags
    /// Gets a list of all database tags.
    ///
    /// GET /fixed/subscriptions/{subscriptionId}/databases/{databaseId}/tags
    pub async fn get_tags(&self, subscription_id: i32, database_id: i32) -> Result<CloudTags> {
        self.client
            .get(&format!(
                "/fixed/subscriptions/{subscription_id}/databases/{database_id}/tags"
            ))
            .await
    }

    /// Add a database tag
    /// Adds a single database tag to a database.
    ///
    /// POST /fixed/subscriptions/{subscriptionId}/databases/{databaseId}/tags
    pub async fn create_tag(
        &self,
        subscription_id: i32,
        database_id: i32,
        request: &DatabaseTagCreateRequest,
    ) -> Result<CloudTag> {
        self.client
            .post(
                &format!("/fixed/subscriptions/{subscription_id}/databases/{database_id}/tags"),
                request,
            )
            .await
    }

    /// Overwrite database tags
    /// Overwrites all tags on the database.
    ///
    /// PUT /fixed/subscriptions/{subscriptionId}/databases/{databaseId}/tags
    pub async fn update_tags(
        &self,
        subscription_id: i32,
        database_id: i32,
        request: &DatabaseTagsUpdateRequest,
    ) -> Result<CloudTags> {
        self.client
            .put(
                &format!("/fixed/subscriptions/{subscription_id}/databases/{database_id}/tags"),
                request,
            )
            .await
    }

    /// Delete database tag
    /// Removes the specified tag from the database.
    ///
    /// DELETE /fixed/subscriptions/{subscriptionId}/databases/{databaseId}/tags/{tagKey}
    pub async fn delete_tag(
        &self,
        subscription_id: i32,
        database_id: i32,
        tag_key: String,
    ) -> Result<HashMap<String, Value>> {
        let response = self
            .client
            .delete_raw(&format!(
                "/fixed/subscriptions/{subscription_id}/databases/{database_id}/tags/{tag_key}"
            ))
            .await?;
        serde_json::from_value(response).map_err(Into::into)
    }

    /// Update database tag value
    /// Updates the value of the specified database tag.
    ///
    /// PUT /fixed/subscriptions/{subscriptionId}/databases/{databaseId}/tags/{tagKey}
    pub async fn update_tag(
        &self,
        subscription_id: i32,
        database_id: i32,
        tag_key: String,
        request: &DatabaseTagUpdateRequest,
    ) -> Result<CloudTag> {
        self.client
            .put(
                &format!(
                    "/fixed/subscriptions/{subscription_id}/databases/{database_id}/tags/{tag_key}"
                ),
                request,
            )
            .await
    }

    // ========================================================================
    // Additional endpoints
    // ========================================================================

    /// Get available target Redis versions for upgrade
    /// Gets a list of Redis versions that the Essentials database can be upgraded to.
    ///
    /// GET /fixed/subscriptions/{subscriptionId}/databases/{databaseId}/available-target-versions
    pub async fn get_available_target_versions(
        &self,
        subscription_id: i32,
        database_id: i32,
    ) -> Result<Value> {
        self.client
            .get_raw(&format!(
                "/fixed/subscriptions/{subscription_id}/databases/{database_id}/available-target-versions"
            ))
            .await
    }

    /// Get Essentials database version upgrade status
    /// Gets information on the latest upgrade attempt for this Essentials database.
    ///
    /// GET /fixed/subscriptions/{subscriptionId}/databases/{databaseId}/upgrade
    pub async fn get_upgrade_status(
        &self,
        subscription_id: i32,
        database_id: i32,
    ) -> Result<Value> {
        self.client
            .get_raw(&format!(
                "/fixed/subscriptions/{subscription_id}/databases/{database_id}/upgrade"
            ))
            .await
    }

    /// Upgrade Essentials database Redis version
    /// Upgrades the specified Essentials database to a later Redis version.
    ///
    /// POST /fixed/subscriptions/{subscriptionId}/databases/{databaseId}/upgrade
    pub async fn upgrade_redis_version(
        &self,
        subscription_id: i32,
        database_id: i32,
        target_version: &str,
    ) -> Result<Value> {
        let request = serde_json::json!({
            "targetVersion": target_version
        });
        self.client
            .post_raw(
                &format!("/fixed/subscriptions/{subscription_id}/databases/{database_id}/upgrade"),
                request,
            )
            .await
    }
}