amberjs 1.16.1

JavaScript/TypeScript runtime built with Rust and V8
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
// Kubernetes Operator Controller
// Implements the reconciliation loop for AmberCluster and AmberWorkload

use std::sync::Arc;

use super::super::crd::{
    AmberCluster, AmberClusterSpec, AmberWorkload, AmberWorkloadSpec, ClusterPhase,
    Condition as AmberCondition, ConditionStatus, ConditionType, WorkloadPhase,
};
use k8s_openapi::api::apps::v1::{StatefulSet, StatefulSetSpec};
use k8s_openapi::api::core::v1::{
    ConfigMap, ConfigMapVolumeSource, Container, ContainerPort, EnvVar, EnvVarSource,
    ObjectFieldSelector, ObjectReference, PersistentVolumeClaim, PersistentVolumeClaimSpec,
    PodSpec, ResourceRequirements, Secret, Service, ServicePort, ServiceSpec, Volume, VolumeMount,
};
use k8s_openapi::apimachinery::pkg::api::resource::Quantity;
use k8s_openapi::apimachinery::pkg::apis::meta::v1::{
    LabelSelector, LabelSelectorRequirement, ObjectMeta,
};
use k8s_openapi::apimachinery::pkg::util::intstr::IntOrString;
use k8s_openapi::ByteString;
use kube::api::{DeleteParams, ListParams, Patch, PatchParams};
use kube::core::object::HasStatus;
use kube::runtime::controller::Action;
use kube::runtime::events::{Event, EventType, Recorder, Reporter};
use kube::{Api, Client, Resource, ResourceExt};
use std::collections::BTreeMap;
use tokio::time::Duration as TokioDuration;
use tracing::{debug, error, info, warn};
/// Cluster controller for managing AmberCluster resources
pub struct ClusterController {
    /// Kubernetes client
    pub client: Client,
    /// API for AmberCluster resources
    pub clusters: Api<AmberCluster>,
    /// API for StatefulSet resources
    pub statefulsets: Api<StatefulSet>,
    /// API for Service resources
    pub services: Api<Service>,
    /// API for ConfigMap resources
    pub configmaps: Api<ConfigMap>,
    /// API for Secret resources
    pub secrets: Api<Secret>,
    /// Event recorder
    pub recorder: Recorder,
}
/// Finalizer name for cluster resources
const CLUSTER_FINALIZER: &str = "amberjsclusters.cloudnative.amberjs.io/finalizer";
impl ClusterController {
    /// Create a new cluster controller
    pub fn new(client: Client, namespace: &str) -> Self {
        let clusters: _ = Api::<AmberCluster>::namespaced(client.clone(), namespace);
        let statefulsets: _ = Api::<StatefulSet>::namespaced(client.clone(), namespace);
        let services: _ =
            Api::<k8s_openapi::api::core::v1::Service>::namespaced(client.clone(), namespace);
        let configmaps: _ =
            Api::<k8s_openapi::api::core::v1::ConfigMap>::namespaced(client.clone(), namespace);
        let secrets: _ =
            Api::<k8s_openapi::api::core::v1::Secret>::namespaced(client.clone(), namespace);
        let reporter: _ = Reporter {
            controller: "amberjs-cluster-controller".to_string(),
            instance: None,
        };
        let recorder: _ = Recorder::new(client.clone(), reporter, ObjectReference::default());
        Self {
            client: client.clone(),
            clusters,
            statefulsets,
            services,
            configmaps,
            secrets,
            recorder,
        }
    }
    /// Reconcile function for AmberCluster
    pub async fn reconcile(&self, cluster: Arc<AmberCluster>) -> Result<Action, Error> {
        info!("Reconciling AmberCluster: {}", cluster.name_any());
        // Check if finalizer exists
        let has_finalizer: _ = cluster.annotations().contains_key(CLUSTER_FINALIZER);
        // Get current phase
        let phase: _ = self.get_current_phase(&cluster).await?;
        debug!("Current phase: {:?}", phase);
        match phase {
            ClusterPhase::Pending | ClusterPhase::Creating => {
                self.reconcile_create(cluster.clone()).await?;
                self.update_phase(cluster.as_ref(), ClusterPhase::Creating)
                    .await?;
            }
            ClusterPhase::Running => {
                self.reconcile_running(cluster.clone()).await?;
            }
            ClusterPhase::Updating => {
                self.reconcile_update(cluster.clone()).await?;
                self.update_phase(cluster.as_ref(), ClusterPhase::Running)
                    .await?;
            }
            ClusterPhase::Failed => {
                if !has_finalizer {
                    // Add finalizer before attempting recovery
                    self.add_finalizer(&cluster).await?;
                }
                self.reconcile_recovery(cluster.clone()).await?;
                self.update_phase(cluster.as_ref(), ClusterPhase::Running)
                    .await?;
            }
        }
        // Add finalizer if it doesn't exist
        if !has_finalizer {
            self.add_finalizer(&cluster).await?;
        }
        Ok(Action::requeue(Duration::from_secs(30)))
    }
    /// Handle cleanup when resource is deleted
    pub async fn cleanup(&self, cluster: Arc<AmberCluster>) -> Result<Action, Error> {
        info!("Cleaning up AmberCluster: {}", cluster.name_any());
        let name: _ = cluster.name_any();
        // Delete StatefulSet
        if let Err(e) = self
            .statefulsets
            .delete(&name, &kube::api::DeleteParams::default())
            .await
        {
            // 404 errors are expected when resource doesn't exist
            if !e.to_string().contains("404") && !e.to_string().contains("NotFound") {
                warn!("Failed to delete StatefulSet: {}", e);
            }
        }
        // Delete Service
        if let Err(e) = self
            .services
            .delete(&name, &kube::api::DeleteParams::default())
            .await
        {
            // 404 errors are expected when resource doesn't exist
            if !e.to_string().contains("404") && !e.to_string().contains("NotFound") {
                warn!("Failed to delete Service: {}", e);
            }
        }
        // Delete ConfigMap
        if let Err(e) = self
            .configmaps
            .delete(&name, &kube::api::DeleteParams::default())
            .await
        {
            // 404 errors are expected when resource doesn't exist
            if !e.to_string().contains("404") && !e.to_string().contains("NotFound") {
                warn!("Failed to delete ConfigMap: {}", e);
            }
        }
        // Delete Secret
        if let Err(e) = self
            .secrets
            .delete(&name, &kube::api::DeleteParams::default())
            .await
        {
            // 404 errors are expected when resource doesn't exist
            if !e.to_string().contains("404") && !e.to_string().contains("NotFound") {
                warn!("Failed to delete Secret: {}", e);
            }
        }
        info!("Successfully cleaned up AmberCluster: {}", name);
        Ok(Action::await_change())
    }
    /// Get current phase of the cluster
    async fn get_current_phase(&self, cluster: &AmberCluster) -> Result<ClusterPhase, Error> {
        // TODO: Implement proper status phase detection
        // For now, always return Pending
        Ok(ClusterPhase::Pending)
    }
    /// Add finalizer to cluster
    async fn add_finalizer(&self, cluster: &AmberCluster) -> Result<(), Error> {
        let patch: _ = Patch::Merge(&serde_json::json!({
            "metadata": {
                "annotations": {
                    CLUSTER_FINALIZER: "true"
                }
            }
        }));
        self.clusters
            .patch(&cluster.name_any(), &PatchParams::default(), &patch)
            .await?;
        Ok(())
    }
    /// Update the phase of the cluster
    async fn update_phase(&self, cluster: &AmberCluster, phase: ClusterPhase) -> Result<(), Error> {
        let is_ready: _ = matches!(phase, ClusterPhase::Running);
        let mut condition = serde_json::Map::new();
        condition.insert(
            "type".to_string(),
            serde_json::Value::String("Ready".to_string()),
        );
        condition.insert(
            "status".to_string(),
            serde_json::Value::String(is_ready.to_string()),
        );
        let mut status = serde_json::Map::new();
        status.insert(
            "phase".to_string(),
            serde_json::Value::String(phase.as_str().to_string()),
        );
        status.insert(
            "conditions".to_string(),
            serde_json::Value::Array(vec![serde_json::Value::Object(condition)]),
        );
        let mut patch_map = serde_json::Map::new();
        patch_map.insert("status".to_string(), serde_json::Value::Object(status));
        let patch: _ = serde_json::Value::Object(patch_map);
        let params: _ = PatchParams::default();
        self.clusters
            .patch_status(&cluster.name_any(), &params, &Patch::Merge(&patch))
            .await?;
        // Emit event
        let event_type: _ = match phase {
            ClusterPhase::Running => EventType::Normal,
            ClusterPhase::Failed => EventType::Warning,
            _ => EventType::Normal,
        };
        self.recorder
            .publish(Event {
                type_: event_type,
                reason: "PhaseChanged".to_string(),
                note: Some(format!("Cluster phase changed to {:?}", phase)),
                action: "Update".to_string(),
                secondary: None,
            })
            .await;
        Ok(())
    }
    /// Reconcile cluster creation
    async fn reconcile_create(&self, cluster: Arc<AmberCluster>) -> Result<(), Error> {
        info!("Creating cluster resources for: {}", cluster.name_any());
        // 1. Create ConfigMap
        self.create_configmap(&cluster).await?;
        // 2. Create Secret
        self.create_secret(&cluster).await?;
        // 3. Create StatefulSet
        self.create_statefulset(&cluster).await?;
        // 4. Create Service
        self.create_service(&cluster).await?;
        // 5. Wait for pods to be ready
        self.wait_for_ready(&cluster).await?;
        info!(
            "Successfully created cluster resources for: {}",
            cluster.name_any()
        );
        Ok(())
    }
    /// Reconcile running cluster
    async fn reconcile_running(&self, cluster: Arc<AmberCluster>) -> Result<(), Error> {
        debug!("Checking cluster status for: {}", cluster.name_any());
        // Check if resources need updating
        if self.needs_update(&cluster).await? {
            info!("Cluster needs update: {}", cluster.name_any());
            self.reconcile_update(cluster.clone()).await?;
        }
        // Check health
        self.check_health(&cluster).await?;
        Ok(())
    }
    /// Reconcile cluster update
    async fn reconcile_update(&self, cluster: Arc<AmberCluster>) -> Result<(), Error> {
        info!("Updating cluster: {}", cluster.name_any());
        // Update StatefulSet if needed
        if let Err(e) = self.update_statefulset(&cluster).await {
            error!("Failed to update StatefulSet: {}", e);
            return Err(e);
        }
        // Wait for update to complete
        self.wait_for_update(&cluster).await?;
        info!("Successfully updated cluster: {}", cluster.name_any());
        Ok(())
    }
    /// Reconcile cluster recovery from failed state
    async fn reconcile_recovery(&self, cluster: Arc<AmberCluster>) -> Result<(), Error> {
        warn!(
            "Recovering cluster from failed state: {}",
            cluster.name_any()
        );
        // Check if resources exist
        if !self.resources_exist(&cluster).await? {
            // Resources don't exist, recreate them
            self.reconcile_create(cluster.clone()).await?;
        } else {
            // Resources exist, try to recover
            self.recover_resources(&cluster).await?;
        }
        Ok(())
    }
    /// Create ConfigMap for cluster configuration
    async fn create_configmap(&self, cluster: &AmberCluster) -> Result<(), Error> {
        let name: _ = cluster.name_any();
        let mut data = BTreeMap::new();
        data.insert("version".to_string(), cluster.spec.version.clone());
        data.insert(
            "clusterName".to_string(),
            cluster.spec.distributed.cluster_name.clone(),
        );
        data.insert("nodes".to_string(), cluster.spec.nodes.to_string());
        let cm: _ = k8s_openapi::api::core::v1::ConfigMap {
            metadata: k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta {
                name: Some(name.clone()),
                namespace: cluster.namespace(),
                labels: Some(self.get_labels(cluster)),
                annotations: Some(self.get_annotations(cluster)),
                ..Default::default()
            },
            data: Some(data),
            binary_data: None,
            immutable: None,
        };
        self.configmaps
            .create(&kube::api::PostParams::default(), &cm)
            .await?;
        info!("Created ConfigMap: {}", name);
        Ok(())
    }
    /// Create Secret for cluster credentials
    async fn create_secret(&self, cluster: &AmberCluster) -> Result<(), Error> {
        let name: _ = cluster.name_any();
        let mut data = BTreeMap::new();
        let encoded: _ = base64::encode("dummy-token");
        data.insert("token".to_string(), ByteString(encoded.into_bytes()));
        let secret: _ = k8s_openapi::api::core::v1::Secret {
            metadata: k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta {
                name: Some(name.clone()),
                namespace: cluster.namespace(),
                labels: Some(self.get_labels(cluster)),
                annotations: Some(self.get_annotations(cluster)),
                ..Default::default()
            },
            data: Some(data),
            string_data: None,
            type_: Some("Opaque".to_string()),
            immutable: None,
        };
        self.secrets
            .create(&kube::api::PostParams::default(), &secret)
            .await?;
        info!("Created Secret: {}", name);
        Ok(())
    }
    /// Create StatefulSet for cluster nodes
    async fn create_statefulset(&self, cluster: &AmberCluster) -> Result<(), Error> {
        let name: _ = cluster.name_any();
        let replicas: _ = cluster.spec.nodes as i32;
        let statefulset: _ = StatefulSet {
            metadata: k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta {
                name: Some(name.clone()),
                namespace: cluster.namespace(),
                labels: Some(self.get_labels(cluster)),
                annotations: Some(self.get_annotations(cluster)),
                ..Default::default()
            },
            spec: Some(StatefulSetSpec {
                replicas: Some(replicas),
                service_name: format!("{}-headless", name),
                ordinals: None,
                selector: k8s_openapi::apimachinery::pkg::apis::meta::v1::LabelSelector {
                    match_labels: Some(self.get_labels(cluster)),
                    match_expressions: None,
                },
                template: k8s_openapi::api::core::v1::PodTemplateSpec {
                    metadata: Some(k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta {
                        labels: Some(self.get_labels(cluster)),
                        annotations: Some(BTreeMap::from([(
                            "amberjs.io/cluster".to_string(),
                            name.clone(),
                        )])),
                        ..Default::default()
                    }),
                    spec: Some(self.create_pod_spec(cluster)?),
                },
                volume_claim_templates: Some(self.create_pvc_templates(cluster)?),
                min_ready_seconds: Some(10),
                persistent_volume_claim_retention_policy: None,
                pod_management_policy: None,
                revision_history_limit: Some(10),
                update_strategy: Some(k8s_openapi::api::apps::v1::StatefulSetUpdateStrategy {
                    type_: Some("RollingUpdate".to_string()),
                    rolling_update: Some(
                        k8s_openapi::api::apps::v1::RollingUpdateStatefulSetStrategy {
                            max_unavailable: Some(
                                k8s_openapi::apimachinery::pkg::util::intstr::IntOrString::Int(1),
                            ),
                            partition: None,
                        },
                    ),
                }),
            }),
            status: None,
        };
        self.statefulsets
            .create(&kube::api::PostParams::default(), &statefulset)
            .await?;
        info!("Created StatefulSet: {} with {} replicas", name, replicas);
        Ok(())
    }
    /// Create Service for cluster access
    async fn create_service(&self, cluster: &AmberCluster) -> Result<(), Error> {
        let name: _ = cluster.name_any();
        // Headless service for StatefulSet
        let headless_service: _ = k8s_openapi::api::core::v1::Service {
            metadata: k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta {
                name: Some(format!("{}-headless", name)),
                namespace: cluster.namespace(),
                labels: Some(self.get_labels(cluster)),
                annotations: Some(self.get_annotations(cluster)),
                ..Default::default()
            },
            spec: Some(k8s_openapi::api::core::v1::ServiceSpec {
                cluster_ip: Some("None".to_string()),
                cluster_ips: None,
                ip_families: None,
                ip_family_policy: None,
                ports: None,
                publish_not_ready_addresses: Some(true),
                selector: Some(self.get_labels(cluster)),
                session_affinity: Some("ClientIP".to_string()),
                session_affinity_config: None,
                type_: Some("ClusterIP".to_string()),
                external_ips: None,
                external_name: None,
                health_check_node_port: None,
                load_balancer_class: None,
                load_balancer_ip: None,
                load_balancer_source_ranges: None,
                allocate_load_balancer_node_ports: None,
                external_traffic_policy: None,
                internal_traffic_policy: None,
            }),
            status: None,
        };
        self.services
            .create(&kube::api::PostParams::default(), &headless_service)
            .await?;
        // ClusterIP service for API access
        let api_service: _ = k8s_openapi::api::core::v1::Service {
            metadata: k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta {
                name: Some(name.clone()),
                namespace: cluster.namespace(),
                labels: Some(self.get_labels(cluster)),
                annotations: Some(self.get_annotations(cluster)),
                ..Default::default()
            },
            spec: Some(k8s_openapi::api::core::v1::ServiceSpec {
                cluster_ip: Some("10.0.0.1".to_string()),
                cluster_ips: None,
                ip_families: None,
                ip_family_policy: None,
                ports: Some(vec![k8s_openapi::api::core::v1::ServicePort {
                    name: Some("api".to_string()),
                    port: 8080,
                    protocol: Some("TCP".to_string()),
                    target_port: Some(
                        k8s_openapi::apimachinery::pkg::util::intstr::IntOrString::Int(8080),
                    ),
                    app_protocol: None,
                    node_port: None,
                }]),
                publish_not_ready_addresses: None,
                selector: Some(self.get_labels(cluster)),
                session_affinity: Some("None".to_string()),
                session_affinity_config: None,
                type_: Some("ClusterIP".to_string()),
                external_ips: None,
                external_name: None,
                health_check_node_port: None,
                load_balancer_class: None,
                load_balancer_ip: None,
                load_balancer_source_ranges: None,
                allocate_load_balancer_node_ports: None,
                external_traffic_policy: None,
                internal_traffic_policy: None,
            }),
            status: None,
        };
        self.services
            .create(&kube::api::PostParams::default(), &api_service)
            .await?;
        info!("Created Services: {}-headless and {}", name, name);
        Ok(())
    }
    /// Check if cluster needs update
    async fn needs_update(&self, cluster: &AmberCluster) -> Result<bool, Error> {
        // TODO: Implement update detection logic
        Ok(false)
    }
    /// Update StatefulSet if needed
    async fn update_statefulset(&self, cluster: &AmberCluster) -> Result<(), Error> {
        // TODO: Implement StatefulSet update logic
        Ok(())
    }
    /// Check cluster health
    async fn check_health(&self, cluster: &AmberCluster) -> Result<(), Error> {
        // TODO: Implement health check logic
        Ok(())
    }
    /// Check if cluster resources exist
    async fn resources_exist(&self, cluster: &AmberCluster) -> Result<bool, Error> {
        let name: _ = cluster.name_any();
        // Check StatefulSet
        if let Err(e) = self.statefulsets.get(&name).await {
            // 404 errors mean resource doesn't exist
            if e.to_string().contains("404") || e.to_string().contains("NotFound") {
                return Ok(false);
            }
            return Err(Error::Kube(e));
        }
        Ok(true)
    }
    /// Recover cluster resources
    async fn recover_resources(&self, cluster: &AmberCluster) -> Result<(), Error> {
        // TODO: Implement resource recovery logic
        Ok(())
    }
    /// Wait for pods to be ready
    async fn wait_for_ready(&self, cluster: &AmberCluster) -> Result<(), Error> {
        // TODO: Implement readiness check
        Ok(())
    }
    /// Wait for update to complete
    async fn wait_for_update(&self, cluster: &AmberCluster) -> Result<(), Error> {
        // TODO: Implement update wait logic
        Ok(())
    }
    /// Create pod specification
    fn create_pod_spec(
        &self,
        cluster: &AmberCluster,
    ) -> Result<k8s_openapi::api::core::v1::PodSpec, Error> {
        Ok(k8s_openapi::api::core::v1::PodSpec {
            containers: vec![k8s_openapi::api::core::v1::Container {
                name: "amberjs".to_string(),
                image: Some(cluster.spec.image.clone()),
                image_pull_policy: Some("IfNotPresent".to_string()),
                ports: Some(vec![k8s_openapi::api::core::v1::ContainerPort {
                    container_port: 8080,
                    protocol: Some("TCP".to_string()),
                    name: Some("api".to_string()),
                    host_ip: None,
                    host_port: None,
                }]),
                env: Some(vec![
                    k8s_openapi::api::core::v1::EnvVar {
                        name: "AMBER_CLUSTER_NAME".to_string(),
                        value: Some(cluster.spec.distributed.cluster_name.clone()),
                        value_from: None,
                    },
                    k8s_openapi::api::core::v1::EnvVar {
                        name: "AMBER_NODE_ID".to_string(),
                        value: None,
                        value_from: Some(k8s_openapi::api::core::v1::EnvVarSource {
                            field_ref: Some(k8s_openapi::api::core::v1::ObjectFieldSelector {
                                field_path: "metadata.name".to_string(),
                                api_version: None,
                            }),
                            resource_field_ref: None,
                            config_map_key_ref: None,
                            secret_key_ref: None,
                        }),
                    },
                ]),
                env_from: None,
                resources: Some(k8s_openapi::api::core::v1::ResourceRequirements {
                    requests: Some(BTreeMap::from([
                        (
                            "cpu".to_string(),
                            Quantity(cluster.spec.resources.cpu.clone()),
                        ),
                        (
                            "memory".to_string(),
                            Quantity(cluster.spec.resources.memory.clone()),
                        ),
                    ])),
                    limits: Some(BTreeMap::from([
                        (
                            "cpu".to_string(),
                            Quantity(cluster.spec.resources.cpu.clone()),
                        ),
                        (
                            "memory".to_string(),
                            Quantity(cluster.spec.resources.memory.clone()),
                        ),
                    ])),
                    claims: None,
                }),
                volume_mounts: Some(vec![k8s_openapi::api::core::v1::VolumeMount {
                    name: "config".to_string(),
                    mount_path: "/etc/amberjs".to_string(),
                    read_only: Some(true),
                    sub_path: None,
                    sub_path_expr: None,
                    mount_propagation: None,
                }]),
                ..Default::default()
            }],
            volumes: Some(vec![k8s_openapi::api::core::v1::Volume {
                name: "config".to_string(),
                config_map: Some(k8s_openapi::api::core::v1::ConfigMapVolumeSource {
                    default_mode: Some(0o644),
                    items: None,
                    name: Some(cluster.name_any()),
                    optional: Some(false),
                }),
                ..Default::default()
            }]),
            ..Default::default()
        })
    }
    /// Create PVC templates
    fn create_pvc_templates(
        &self,
        cluster: &AmberCluster,
    ) -> Result<Vec<k8s_openapi::api::core::v1::PersistentVolumeClaim>, Error> {
        let mut pvcs = Vec::new();
        // Add storage PVC if disk size is specified
        if !cluster.spec.resources.disk.is_empty() {
            let pvc: _ = k8s_openapi::api::core::v1::PersistentVolumeClaim {
                metadata: k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta {
                    name: Some(format!("{}-data", cluster.name_any())),
                    ..Default::default()
                },
                spec: Some(k8s_openapi::api::core::v1::PersistentVolumeClaimSpec {
                    access_modes: Some(vec!["ReadWriteOnce".to_string()]),
                    resources: Some(k8s_openapi::api::core::v1::ResourceRequirements {
                        requests: Some(BTreeMap::from([(
                            "storage".to_string(),
                            Quantity(cluster.spec.resources.disk.clone()),
                        )])),
                        limits: None,
                        claims: None,
                    }),
                    storage_class_name: Some("standard".to_string()),
                    selector: None,
                    volume_mode: None,
                    volume_name: None,
                    data_source: None,
                    data_source_ref: None,
                }),
                status: None,
            };
            pvcs.push(pvc);
        }
        Ok(pvcs)
    }
    /// Get labels for resources
    fn get_labels(
        &self,
        cluster: &AmberCluster,
    ) -> BTreeMap<
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
    > {
        BTreeMap::from([
            ("amberjs.io/cluster".to_string(), cluster.name_any()),
            (
                "amberjs.io/version".to_string(),
                cluster.spec.version.clone(),
            ),
            (
                "amberjs.io/cluster-name".to_string(),
                cluster.spec.distributed.cluster_name.clone(),
            ),
        ])
    }
    /// Get annotations for resources
    fn get_annotations(
        &self,
        cluster: &AmberCluster,
    ) -> BTreeMap<
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        String,
    > {
        BTreeMap::from([
            (
                "amberjs.io/created-by".to_string(),
                "amberjs-operator".to_string(),
            ),
            (
                "amberjs.io/description".to_string(),
                "Amber Cluster".to_string(),
            ),
        ])
    }
}
/// Error type for operator controller
#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("Kubernetes error: {0}")]
    Kube(#[from] kube::Error),
    #[error("Serde JSON error: {0}")]
    Json(#[from] serde_json::Error),
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
    #[error("Other error: {0}")]
    Other(String),
}
#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::{BTreeMap, HashMap};
    use std::time::Duration;
    #[test]
    fn test_error_type() {
        // Test error conversion - just verify the error type exists
        // This test validates that the Error enum properly wraps kube::Error
        let _error: _ = Error::Other("test".to_string());
        // The actual conversion test would require constructing a real kube::Error
        // which is complex, so we just verify the types compile correctly
    }
}