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
use k8s_openapi::{
    api::core::v1::ResourceRequirements,
    apimachinery::pkg::{api::resource::Quantity, util::intstr::IntOrString},
};
use std::collections::BTreeMap;

use crate::apis::coredb_types::CoreDB;
use crate::{
    apis::coredb_types::{
        Backup, ConnectionPooler, PgBouncer, S3Credentials, ServiceAccountTemplate, VolumeSnapshot,
    },
    cloudnativepg::poolers::{PoolerPgbouncerPoolMode, PoolerTemplateSpecContainersResources},
    extensions::types::{Extension, TrunkInstall},
    stacks::{types::ImagePerPgVersion, DATAWAREHOUSE, ML, STANDARD},
};

pub fn default_replicas() -> i32 {
    1
}

pub fn default_resources() -> ResourceRequirements {
    let limits: BTreeMap<String, Quantity> = BTreeMap::from([
        ("cpu".to_owned(), Quantity("2".to_string())),
        ("memory".to_owned(), Quantity("2Gi".to_string())),
    ]);
    let requests: BTreeMap<String, Quantity> = BTreeMap::from([
        ("cpu".to_owned(), Quantity("500m".to_string())),
        ("memory".to_owned(), Quantity("512Mi".to_string())),
    ]);
    ResourceRequirements {
        limits: Some(limits),
        requests: Some(requests),
    }
}

pub fn default_postgres_exporter_enabled() -> bool {
    false
}

pub fn default_uid() -> i32 {
    999
}

pub fn default_port() -> i32 {
    5432
}

pub fn default_repository() -> String {
    "quay.io/tembo".to_owned()
}

pub fn default_images() -> ImagePerPgVersion {
    // Note: this will recurse infinitely if standard.yaml doesn't have `images` set
    STANDARD.images.clone()
}

pub fn default_llm_image() -> String {
    ML.images.pg15.clone()
}

pub fn default_dw_image() -> String {
    DATAWAREHOUSE.images.pg15.clone()
}

pub fn default_image_uri() -> String {
    let repo = default_repository();
    let image = default_images();
    let image_for_pg_15 = image.pg15;
    format!("{}/{}", repo, image_for_pg_15)
}

pub fn default_llm_image_uri() -> String {
    let repo = default_repository();
    let image = default_llm_image();
    format!("{}/{}", repo, image)
}

pub fn default_dw_image_uri() -> String {
    let repo = default_repository();
    let image = default_dw_image();
    format!("{}/{}", repo, image)
}

pub fn postgres_major_version_from_cdb(coredb: &CoreDB) -> Result<i32, String> {
    let image = coredb.spec.image.clone();
    parse_postgres_major_version(&image)
}
pub fn parse_postgres_major_version(image: &str) -> Result<i32, String> {
    let parts: Vec<&str> = image.split(':').collect();
    if parts.len() != 2 {
        return Err("Invalid image format".to_string());
    }
    let version_part = parts[1];
    let version_section = version_part
        .split('-')
        .next()
        .ok_or("Version section not found")?;
    let version_numbers: Vec<&str> = version_section.split('.').collect();
    if version_numbers.is_empty() {
        return Err("Version number not found".to_string());
    }
    match version_numbers[0].parse::<i32>() {
        Ok(major_version) => Ok(major_version),
        Err(_) => Err("Failed to parse major version".to_string()),
    }
}

pub fn default_storage() -> Quantity {
    Quantity("8Gi".to_string())
}

pub fn default_sharedir_storage() -> Quantity {
    Quantity("1Gi".to_string())
}

pub fn default_pkglibdir_storage() -> Quantity {
    Quantity("1Gi".to_string())
}

pub fn default_postgres_exporter_image() -> String {
    "quay.io/prometheuscommunity/postgres-exporter:v0.12.0".to_owned()
}

pub fn default_postgres_exporter_target_databases() -> Vec<String> {
    vec!["postgres".to_owned()]
}

pub fn default_extensions() -> Vec<Extension> {
    vec![]
}

pub fn default_trunk_installs() -> Vec<TrunkInstall> {
    vec![]
}

pub fn default_database() -> String {
    "postgres".to_owned()
}

pub fn default_schema() -> String {
    "public".to_owned()
}

pub fn default_description() -> Option<String> {
    Some("No description provided".to_owned())
}

pub fn default_stop() -> bool {
    false
}

pub fn default_extensions_updating() -> bool {
    false
}

pub fn default_service_account_template() -> ServiceAccountTemplate {
    ServiceAccountTemplate { metadata: None }
}

pub fn default_backup() -> Backup {
    Backup {
        destinationPath: default_destination_path(),
        encryption: default_encryption(),
        retentionPolicy: default_retention_policy(),
        schedule: default_backup_schedule(),
        s3_credentials: default_s3_credentials(),
        volume_snapshot: default_volume_snapshot(),
        ..Default::default()
    }
}

pub fn default_destination_path() -> Option<String> {
    Some("s3://".to_string())
}

pub fn default_encryption() -> Option<String> {
    Some("AES256".to_owned())
}

pub fn default_retention_policy() -> Option<String> {
    Some("30".to_owned())
}

pub fn default_backup_schedule() -> Option<String> {
    // Every day at midnight
    Some("0 0 * * *".to_owned())
}

pub fn default_conn_pooler() -> ConnectionPooler {
    ConnectionPooler {
        enabled: default_conn_pooler_enabled(),
        pooler: default_pgbouncer(),
    }
}

pub fn default_conn_pooler_enabled() -> bool {
    false
}

pub fn default_pool_mode() -> PoolerPgbouncerPoolMode {
    PoolerPgbouncerPoolMode::Transaction
}

pub fn default_pooler_parameters() -> BTreeMap<String, String> {
    BTreeMap::from([
        ("default_pool_size".to_string(), "50".to_string()),
        ("max_client_conn".to_string(), "5000".to_string()),
    ])
}

pub fn default_pooler_resources() -> PoolerTemplateSpecContainersResources {
    PoolerTemplateSpecContainersResources {
        claims: None,
        limits: Some(BTreeMap::from([
            ("cpu".to_owned(), IntOrString::String("100m".to_owned())),
            ("memory".to_owned(), IntOrString::String("128Mi".to_owned())),
        ])),
        requests: Some(BTreeMap::from([
            ("cpu".to_owned(), IntOrString::String("50m".to_owned())),
            ("memory".to_owned(), IntOrString::String("64Mi".to_owned())),
        ])),
    }
}

pub fn default_pgbouncer() -> PgBouncer {
    PgBouncer {
        poolMode: default_pool_mode(),
        parameters: Some(default_pooler_parameters()),
        resources: Some(default_pooler_resources()),
    }
}

pub fn default_s3_credentials() -> Option<S3Credentials> {
    Some(S3Credentials {
        inherit_from_iam_role: Some(true),
        ..Default::default()
    })
}

pub fn default_volume_snapshot() -> Option<VolumeSnapshot> {
    Some(VolumeSnapshot {
        enabled: false,
        snapshot_class: None,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_postgres_major_version() {
        let examples = vec![
            (
                "387894460527.dkr.ecr.us-east-1.amazonaws.com/tembo-io/standard-cnpg:16.1-d15f2dc",
                16,
            ),
            ("quay.io/tembo-io/standard-cnpg:14.10-d15f2dc", 14),
            (
                "387894460527.dkr.ecr.us-east-1.amazonaws.com/tembo-io/standard-cnpg:15-a0a5ab5",
                15,
            ),
        ];

        for (input, expected) in examples {
            assert_eq!(parse_postgres_major_version(input).unwrap(), expected);
        }

        // Test for error handling
        assert!(parse_postgres_major_version("invalid/image/format").is_err());
        // Adding a test case for error handling when version section is not found
        assert!(parse_postgres_major_version(
            "387894460527.dkr.ecr.us-east-1.amazonaws.com/tembo-io/standard-cnpg:"
        )
        .is_err());
    }
}