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
use crate::{
    apis::coredb_types::{CoreDB, CoreDBStatus},
    extensions::types::{ExtensionInstallLocationStatus, ExtensionStatus, TrunkInstallStatus},
    get_current_coredb_resource, patch_cdb_status_merge, Context,
};
use kube::{runtime::controller::Action, Api};
use serde_json::json;
use std::{sync::Arc, time::Duration};
use tracing::{debug, error, info, instrument, warn};

pub async fn update_extension_location_in_status(
    cdb: &CoreDB,
    ctx: Arc<Context>,
    extension_name: &str,
    new_location_status: &ExtensionInstallLocationStatus,
) -> Result<Vec<ExtensionStatus>, Action> {
    let cdb = get_current_coredb_resource(cdb, ctx.clone()).await?;
    let current_extensions_status = match &cdb.status {
        None => {
            error!("status should always already be present when merging one extension location into existing status");
            return Err(Action::requeue(Duration::from_secs(300)));
        }
        Some(status) => match &status.extensions {
            None => {
                error!("status.extensions should always already be present when merging one extension location into existing status");
                return Err(Action::requeue(Duration::from_secs(300)));
            }
            Some(extensions) => extensions.clone(),
        },
    };
    let new_extensions_status = merge_location_status_into_extension_status_list(
        extension_name,
        new_location_status,
        current_extensions_status,
    );
    update_extensions_status(&cdb, new_extensions_status.clone(), &ctx).await?;
    Ok(new_extensions_status.clone())
}

// Given a location status, set it in a provided list of extension statuses,
// replacing the current value if found, or creating the location and / or extension
// if not found.
pub fn merge_location_status_into_extension_status_list(
    extension_name: &str,
    new_location_status: &ExtensionInstallLocationStatus,
    current_extensions_status: Vec<ExtensionStatus>,
) -> Vec<ExtensionStatus> {
    let mut new_extensions_status = current_extensions_status.clone();
    for extension in &mut new_extensions_status {
        // If the extension is already in the status list
        if extension.name == extension_name {
            for location in &mut extension.locations {
                // If the location is already in the status list
                if location.database == new_location_status.database {
                    // Then replace it
                    *location = new_location_status.clone();
                    return new_extensions_status;
                }
            }
            // If we never found the location, append it to existing extension status
            extension.locations.push(new_location_status.clone());
            // Then sort the locations alphabetically by database name
            // sort locations by database and schema so the order is deterministic
            extension.locations.sort_by(|a, b| a.database.cmp(&b.database));
            return new_extensions_status;
        }
    }
    // If we never found the extension status, append it
    new_extensions_status.push(ExtensionStatus {
        name: extension_name.to_string(),
        description: None,
        locations: vec![new_location_status.clone()],
    });
    // Then sort alphabetically by name
    new_extensions_status.sort_by(|a, b| a.name.cmp(&b.name));
    new_extensions_status
}

pub async fn update_extensions_status(
    cdb: &CoreDB,
    ext_status_updates: Vec<ExtensionStatus>,
    ctx: &Arc<Context>,
) -> Result<(), Action> {
    let patch_status = json!({
        "apiVersion": "coredb.io/v1alpha1",
        "kind": "CoreDB",
        "status": {
            "extensions": ext_status_updates
        }
    });
    let coredb_api: Api<CoreDB> = Api::namespaced(
        ctx.client.clone(),
        &cdb.metadata
            .namespace
            .clone()
            .expect("CoreDB should have a namespace"),
    );
    patch_cdb_status_merge(
        &coredb_api,
        &cdb.metadata
            .name
            .clone()
            .expect("CoreDB should always have a name"),
        patch_status,
    )
    .await?;
    Ok(())
}

#[instrument(skip(cdb))]
pub async fn remove_trunk_installs_from_status(
    cdb: &Api<CoreDB>,
    name: &str,
    trunk_install_names: Vec<String>,
) -> crate::Result<(), Action> {
    if trunk_install_names.is_empty() {
        debug!("No trunk installs to remove from status on {}", name);
        return Ok(());
    }
    info!(
        "Removing trunk installs {:?} from status on {}",
        trunk_install_names, name
    );
    let current_coredb = cdb.get(name).await.map_err(|e| {
        error!("Error getting CoreDB: {:?}", e);
        Action::requeue(Duration::from_secs(10))
    })?;
    let current_status = match current_coredb.status {
        None => {
            warn!(
                "Did not find current status, initializing an empty status {}",
                name
            );
            CoreDBStatus::default()
        }
        Some(status) => status,
    };
    let current_trunk_installs = match current_status.trunk_installs {
        None => {
            warn!(
                "Trunk installs on status is None for {}, but we are trying remove from status {:?}",
                name, trunk_install_names
            );
            return Ok(());
        }
        Some(trunk_installs) => trunk_installs,
    };
    if current_trunk_installs.is_empty() {
        warn!(
            "No trunk installs in status is an empty list {}, but we are trying remove from status {:?}",
            name, trunk_install_names
        );
        return Ok(());
    } else {
        info!(
            "There are currently {} trunk installs in status, and we are removing {} for {}",
            current_trunk_installs.len(),
            trunk_install_names.len(),
            name
        );
    }
    let mut new_trunk_installs_status = current_trunk_installs.clone();

    // Remove the trunk installs from the status
    for trunk_install_name in trunk_install_names {
        new_trunk_installs_status.retain(|t| t.name != trunk_install_name);
    }

    // sort alphabetically by name
    new_trunk_installs_status.sort_by(|a, b| a.name.cmp(&b.name));
    // remove duplicates
    new_trunk_installs_status.dedup_by(|a, b| a.name == b.name);

    info!(
        "The new status will have {} trunk installs: {}",
        new_trunk_installs_status.len(),
        name
    );
    let new_status = CoreDBStatus {
        trunk_installs: Some(new_trunk_installs_status),
        ..current_status
    };
    let patch_status = json!({
        "apiVersion": "coredb.io/v1alpha1",
        "kind": "CoreDB",
        "status": new_status
    });
    patch_cdb_status_merge(cdb, name, patch_status).await?;
    info!("Patched status for {}", name);
    Ok(())
}

pub async fn add_trunk_install_to_status(
    cdb: &Api<CoreDB>,
    name: &str,
    new_trunk_install_status_to_include: &TrunkInstallStatus,
) -> crate::Result<Vec<TrunkInstallStatus>, Action> {
    debug!(
        "Adding trunk install {:?} to status on {}",
        new_trunk_install_status_to_include, name
    );

    let current_coredb = cdb.get(name).await.map_err(|e| {
        error!("Error getting CoreDB: {:?}", e);
        Action::requeue(Duration::from_secs(10))
    })?;

    let current_status = match current_coredb.status {
        None => {
            warn!(
                "While adding trunk install, did not find current status, initializing an empty status {}",
                name
            );
            CoreDBStatus::default()
        }
        Some(status) => status,
    };

    let current_trunk_installs = match current_status.trunk_installs {
        None => {
            warn!(
                "While adding trunk install, trunk installs on status is None for {}, initializing an empty list",
                name
            );
            vec![]
        }
        Some(trunk_installs) => trunk_installs,
    };

    info!(
        "There are currently {} trunk installs in status for {}",
        current_trunk_installs.len(),
        name
    );

    let updated_trunk_installs_status =
        update_trunk_installs(current_trunk_installs, new_trunk_install_status_to_include);

    info!(
        "The new status will have {} trunk installs: {}",
        updated_trunk_installs_status.len(),
        name
    );

    let new_status = CoreDBStatus {
        trunk_installs: Some(updated_trunk_installs_status.clone()),
        ..current_status
    };

    let patch_status = json!({
        "apiVersion": "coredb.io/v1alpha1",
        "kind": "CoreDB",
        "status": new_status
    });

    patch_cdb_status_merge(cdb, name, patch_status).await?;

    Ok(updated_trunk_installs_status)
}

fn update_trunk_installs(
    current_trunk_installs: Vec<TrunkInstallStatus>,
    new_trunk_install: &TrunkInstallStatus,
) -> Vec<TrunkInstallStatus> {
    let mut updated_trunk_installs: Vec<TrunkInstallStatus> = vec![];

    for existing_status in &current_trunk_installs {
        if existing_status.name == new_trunk_install.name
            && existing_status.version == new_trunk_install.version
        {
            // Update existing status
            let mut update_status = existing_status.clone();
            if update_status.installed_to_pods.is_none() {
                update_status.installed_to_pods = Some(vec![]);
            }
            if let Some(ref mut installed_to_pods) = update_status.installed_to_pods {
                if let Some(new_instances) = &new_trunk_install.installed_to_pods {
                    installed_to_pods.extend_from_slice(new_instances);
                    installed_to_pods.sort();
                    installed_to_pods.dedup();
                }
            }
            updated_trunk_installs.push(update_status);
        } else {
            updated_trunk_installs.push(existing_status.clone());
        }
    }

    // If the trunk install status was not found, add it
    if !updated_trunk_installs
        .iter()
        .any(|status| status.name == new_trunk_install.name)
    {
        updated_trunk_installs.push(new_trunk_install.clone());
    }

    // sort alphabetically by name
    updated_trunk_installs.sort_by(|a, b| a.name.cmp(&b.name));
    updated_trunk_installs.clone()
}

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

    #[test]
    fn test_update_trunk_installs_from_no_pods() {
        let current_trunk_installs = vec![TrunkInstallStatus {
            name: "pg_stat_statements".to_string(),
            version: Some("1.0".to_string()),
            error: false,
            error_message: None,
            installed_to_pods: None,
        }];
        let new_trunk_install = TrunkInstallStatus {
            name: "pg_stat_statements".to_string(),
            version: Some("1.0".to_string()),
            error: false,
            error_message: None,
            installed_to_pods: Some(vec!["pod-1".to_string(), "pod-2".to_string()]),
        };

        let updated_trunk_installs = update_trunk_installs(current_trunk_installs, &new_trunk_install);

        assert_eq!(updated_trunk_installs.clone().len(), 1);
        assert_eq!(
            updated_trunk_installs[0].installed_to_pods.clone().unwrap().len(),
            2
        );
    }

    #[test]
    fn test_add_new_trunk_install_with_same_name_new_host() {
        let initial_trunk_installs = vec![TrunkInstallStatus {
            error: false,
            installed_to_pods: Some(vec!["test-coredb-24631-1".to_string()]),
            name: "test_name".to_string(),
            version: Some("1.0.0".to_string()),
            error_message: None,
        }];

        let new_trunk_install = TrunkInstallStatus {
            error: false,
            installed_to_pods: Some(vec!["test-coredb-24631-2".to_string()]),
            name: "test_name".to_string(),
            version: Some("1.0.0".to_string()),
            error_message: None,
        };

        let updated_trunk_installs =
            update_trunk_installs(initial_trunk_installs.clone(), &new_trunk_install);

        assert_eq!(
            updated_trunk_installs[0].installed_to_pods,
            Some(vec![
                "test-coredb-24631-1".to_string(),
                "test-coredb-24631-2".to_string(),
            ])
        );
    }

    #[test]
    fn test_add_new_trunk_install_with_diff_names_new_host() {
        let initial_trunk_installs = vec![
            TrunkInstallStatus {
                error: false,
                installed_to_pods: Some(vec![
                    "test-coredb-24631-1".to_string(),
                    "test-coredb-24631-2".to_string(),
                ]),
                name: "test_name".to_string(),
                version: Some("1.0.0".to_string()),
                error_message: None,
            },
            TrunkInstallStatus {
                error: false,
                installed_to_pods: Some(vec!["test-coredb-24631-1".to_string()]),
                name: "test_name2".to_string(),
                version: Some("1.0.0".to_string()),
                error_message: None,
            },
        ];

        let new_trunk_install = TrunkInstallStatus {
            error: false,
            installed_to_pods: Some(vec!["test-coredb-24631-2".to_string()]),
            name: "test_name2".to_string(),
            version: Some("1.0.0".to_string()),
            error_message: None,
        };

        let updated_trunk_installs =
            update_trunk_installs(initial_trunk_installs.clone(), &new_trunk_install);

        assert_eq!(
            updated_trunk_installs[0].installed_to_pods,
            Some(vec![
                "test-coredb-24631-1".to_string(),
                "test-coredb-24631-2".to_string(),
            ])
        );
        assert_eq!(
            updated_trunk_installs[1].installed_to_pods,
            Some(vec![
                "test-coredb-24631-1".to_string(),
                "test-coredb-24631-2".to_string(),
            ])
        );
    }

    #[test]
    fn test_add_new_trunk_install_test2() {
        let initial_trunk_installs = vec![
            TrunkInstallStatus {
                error: false,
                installed_to_pods: Some(vec!["test-coredb-24631-1".to_string()]),
                name: "pg_partman".to_string(),
                version: Some("4.7.3".to_string()),
                error_message: None,
            },
            TrunkInstallStatus {
                error: false,
                installed_to_pods: Some(vec!["test-coredb-24631-1".to_string()]),
                name: "pg_stat_statements".to_string(),
                version: Some("1.10.0".to_string()),
                error_message: None,
            },
            TrunkInstallStatus {
                error: false,
                installed_to_pods: Some(vec!["test-coredb-24631-1".to_string()]),
                name: "pgmq".to_string(),
                version: Some("0.10.0".to_string()),
                error_message: None,
            },
        ];

        let new_trunk_install = TrunkInstallStatus {
            error: false,
            installed_to_pods: Some(vec!["test-coredb-24631-2".to_string()]),
            name: "pg_partman".to_string(),
            version: Some("4.7.3".to_string()),
            error_message: None,
        };

        let updated_trunk_installs =
            update_trunk_installs(initial_trunk_installs.clone(), &new_trunk_install);

        println!("updated_trunk_installs: {:?}", updated_trunk_installs);

        assert_eq!(
            updated_trunk_installs[0].installed_to_pods,
            Some(vec![
                "test-coredb-24631-1".to_string(),
                "test-coredb-24631-2".to_string(),
            ])
        );

        let new_trunk_install = TrunkInstallStatus {
            error: false,
            installed_to_pods: Some(vec!["test-coredb-24631-2".to_string()]),
            name: "pg_stat_statements".to_string(),
            version: Some("1.10.0".to_string()),
            error_message: None,
        };

        let updated_trunk_installs =
            update_trunk_installs(updated_trunk_installs.clone(), &new_trunk_install);

        println!("updated_trunk_installs: {:?}", updated_trunk_installs);

        assert_eq!(
            updated_trunk_installs[1].installed_to_pods,
            Some(vec![
                "test-coredb-24631-1".to_string(),
                "test-coredb-24631-2".to_string(),
            ])
        );

        let new_trunk_install = TrunkInstallStatus {
            error: false,
            installed_to_pods: Some(vec!["test-coredb-24631-2".to_string()]),
            name: "pgmq".to_string(),
            version: Some("0.10.0".to_string()),
            error_message: None,
        };

        let updated_trunk_installs =
            update_trunk_installs(updated_trunk_installs.clone(), &new_trunk_install);

        println!("updated_trunk_installs: {:?}", updated_trunk_installs);

        assert_eq!(
            updated_trunk_installs[2].installed_to_pods,
            Some(vec![
                "test-coredb-24631-1".to_string(),
                "test-coredb-24631-2".to_string(),
            ])
        );
    }
}