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
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::fmt;
use std::fmt::Debug;
use std::marker::PhantomData;

use serde::de::{DeserializeOwned, Deserializer};
use serde::Deserialize;
use serde::Serialize;

use crate::Spec;

pub const DEFAULT_NS: &str = "default";
pub const TYPE_OPAQUE: &str = "Opaque";

pub trait K8Meta {
    /// resource name
    fn name(&self) -> &str;

    /// namespace
    fn namespace(&self) -> &str;
}

pub trait LabelProvider: Sized {
    fn set_label_map(self, labels: HashMap<String, String>) -> Self;

    /// helper for setting list of labels
    fn set_labels<T: ToString>(self, labels: Vec<(T, T)>) -> Self {
        let mut label_map = HashMap::new();
        for (key, value) in labels {
            label_map.insert(key.to_string(), value.to_string());
        }
        self.set_label_map(label_map)
    }
}

/// metadata associated with object when returned
/// here name and namespace must be populated
#[derive(Deserialize, Serialize, PartialEq, Debug, Default, Clone)]
#[serde(rename_all = "camelCase", default)]
pub struct ObjectMeta {
    // mandatory fields
    pub name: String,
    pub namespace: String,
    pub uid: String,
    pub creation_timestamp: String,
    pub generation: Option<i32>,
    pub resource_version: String,
    // optional
    pub cluster_name: Option<String>,
    pub deletion_timestamp: Option<String>,
    pub deletion_grace_period_seconds: Option<u32>,
    pub labels: HashMap<String, String>,
    pub owner_references: Vec<OwnerReferences>,
    pub annotations: HashMap<String, String>,
    pub finalizers: Vec<String>,
}

impl LabelProvider for ObjectMeta {
    fn set_label_map(mut self, labels: HashMap<String, String>) -> Self {
        self.labels = labels;
        self
    }
}

impl K8Meta for ObjectMeta {
    fn name(&self) -> &str {
        &self.name
    }

    fn namespace(&self) -> &str {
        &self.namespace
    }
}

impl ObjectMeta {
    pub fn new<S>(name: S, name_space: S) -> Self
    where
        S: Into<String>,
    {
        Self {
            name: name.into(),
            namespace: name_space.into(),
            ..Default::default()
        }
    }

    /// provide builder pattern setter
    pub fn set_labels<T: Into<String>>(mut self, labels: Vec<(T, T)>) -> Self {
        let mut label_map = HashMap::new();
        for (key, value) in labels {
            label_map.insert(key.into(), value.into());
        }
        self.labels = label_map;
        self
    }

    /// create with name and default namespace
    pub fn named<S>(name: S) -> Self
    where
        S: Into<String>,
    {
        Self {
            name: name.into(),
            ..Default::default()
        }
    }

    /// create owner references point to this metadata
    /// if name or uid doesn't exists return none
    pub fn make_owner_reference<S: Spec>(&self) -> OwnerReferences {
        OwnerReferences {
            kind: S::kind(),
            name: self.name.clone(),
            uid: self.uid.clone(),
            // controller: Some(true),
            ..Default::default()
        }
    }

    pub fn namespace(&self) -> &str {
        &self.namespace
    }

    /// create child references that points to this
    pub fn make_child_input_metadata<S: Spec>(&self, childname: String) -> InputObjectMeta {
        let mut owner_refs: Vec<OwnerReferences> = vec![];
        owner_refs.push(self.make_owner_reference::<S>());

        InputObjectMeta {
            name: childname,
            namespace: self.namespace().to_owned(),
            owner_references: owner_refs,
            ..Default::default()
        }
    }

    pub fn as_input(&self) -> InputObjectMeta {
        InputObjectMeta {
            name: self.name.clone(),
            namespace: self.namespace.clone(),
            ..Default::default()
        }
    }

    pub fn as_item(&self) -> ItemMeta {
        ItemMeta {
            name: self.name.clone(),
            namespace: self.namespace.clone(),
        }
    }

    pub fn as_update(&self) -> UpdateItemMeta {
        UpdateItemMeta {
            name: self.name.clone(),
            namespace: self.namespace.clone(),
            resource_version: self.resource_version.clone(),
        }
    }
}

#[derive(Deserialize, Serialize, Debug, Default, Clone)]
#[serde(rename_all = "camelCase")]
pub struct InputObjectMeta {
    pub name: String,
    pub labels: HashMap<String, String>,
    pub namespace: String,
    pub owner_references: Vec<OwnerReferences>,
    pub finalizers: Vec<String>,
    pub annotations: HashMap<String, String>,
}

impl LabelProvider for InputObjectMeta {
    fn set_label_map(mut self, labels: HashMap<String, String>) -> Self {
        self.labels = labels;
        self
    }
}

impl fmt::Display for InputObjectMeta {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}:{}", self.name, self.namespace)
    }
}

impl K8Meta for InputObjectMeta {
    fn name(&self) -> &str {
        &self.name
    }

    fn namespace(&self) -> &str {
        &self.namespace
    }
}

impl InputObjectMeta {
    // shorthand to create just with name and metadata
    pub fn named<S: Into<String>>(name: S, namespace: S) -> Self {
        InputObjectMeta {
            name: name.into(),
            namespace: namespace.into(),
            ..Default::default()
        }
    }
}

impl From<ObjectMeta> for InputObjectMeta {
    fn from(meta: ObjectMeta) -> Self {
        Self {
            name: meta.name,
            namespace: meta.namespace,
            ..Default::default()
        }
    }
}

/// used for retrieving,updating and deleting item
#[derive(Deserialize, Serialize, Debug, Default, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ItemMeta {
    pub name: String,
    pub namespace: String,
}

impl From<ObjectMeta> for ItemMeta {
    fn from(meta: ObjectMeta) -> Self {
        Self {
            name: meta.name,
            namespace: meta.namespace,
        }
    }
}

/// used for updating item
#[derive(Deserialize, Serialize, Debug, Default, Clone)]
#[serde(rename_all = "camelCase")]
pub struct UpdateItemMeta {
    pub name: String,
    pub namespace: String,
    pub resource_version: String,
}

impl From<ObjectMeta> for UpdateItemMeta {
    fn from(meta: ObjectMeta) -> Self {
        Self {
            name: meta.name,
            namespace: meta.namespace,
            resource_version: meta.resource_version,
        }
    }
}

#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct OwnerReferences {
    pub api_version: String,
    #[serde(default)]
    pub block_owner_deletion: bool,
    pub controller: Option<bool>,
    pub kind: String,
    pub name: String,
    pub uid: String,
}

impl Default for OwnerReferences {
    fn default() -> Self {
        Self {
            api_version: "v1".to_owned(),
            block_owner_deletion: false,
            controller: None,
            kind: "".to_owned(),
            uid: "".to_owned(),
            name: "".to_owned(),
        }
    }
}

#[derive(Debug, Clone)]
pub enum DeleteStatus<S>
where
    S: Spec,
{
    Deleted(DeletedStatus),
    ForegroundDelete(K8Obj<S>),
}

/// status for actual deletion
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct DeletedStatus {
    pub api_version: String,
    pub code: Option<u16>,
    pub details: Option<StatusDetails>,
    pub kind: String,
    pub message: Option<String>,
    pub reason: Option<String>,
    pub status: StatusEnum,
}

/// Default status implementation
#[derive(Deserialize, Debug, Eq, PartialEq, Clone)]
pub enum StatusEnum {
    #[serde(rename = "Success")]
    SUCCESS,
    #[serde(rename = "Failure")]
    FAILURE,
}

/*
#[serde(deserialize_with = "StatusEnum::deserialize_with")]
    pub status: StatusEnum,
*/

#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct StatusDetails {
    pub name: String,
    pub group: Option<String>,
    pub kind: String,
    pub uid: String,
}

#[derive(Deserialize, Serialize, Debug, Default, Clone)]
#[serde(rename_all = "camelCase")]
#[serde(bound(serialize = "S: Serialize"))]
#[serde(bound(deserialize = "S: DeserializeOwned"))]
pub struct K8Obj<S>
where
    S: Spec,
{
    #[serde(default = "S::api_version")]
    pub api_version: String,
    #[serde(default = "S::kind")]
    pub kind: String,
    #[serde(default)]
    pub metadata: ObjectMeta,
    #[serde(default)]
    pub spec: S,
    #[serde(flatten)]
    pub header: S::Header,
    #[serde(default)]
    pub status: S::Status,
}

impl<S> K8Obj<S>
where
    S: Spec,
{
    #[allow(dead_code)]
    pub fn new<N>(name: N, spec: S) -> Self
    where
        N: Into<String>,
    {
        Self {
            api_version: S::api_version(),
            kind: S::kind(),
            metadata: ObjectMeta::named(name),
            spec,
            ..Default::default()
        }
    }

    #[allow(dead_code)]
    pub fn set_status(mut self, status: S::Status) -> Self {
        self.status = status;
        self
    }

    pub fn as_status_update(&self, status: S::Status) -> UpdateK8ObjStatus<S> {
        UpdateK8ObjStatus {
            api_version: S::api_version(),
            kind: S::kind(),
            metadata: self.metadata.as_update(),
            status,
            ..Default::default()
        }
    }
}

impl<S> K8Obj<S>
where
    S: Spec,
{
    pub fn as_input(&self) -> InputK8Obj<S> {
        K8SpecObj {
            api_version: self.api_version.clone(),
            kind: self.kind.clone(),
            metadata: self.metadata.as_input(),
            spec: self.spec.clone(),
            ..Default::default()
        }
    }
}

/// For creating, only need spec
#[derive(Deserialize, Serialize, Debug, Default, Clone)]
#[serde(rename_all = "camelCase")]
pub struct K8SpecObj<S, M> {
    pub api_version: String,
    pub kind: String,
    pub metadata: M,
    pub spec: S,
    #[serde(default)]
    pub data: BTreeMap<String, String>,
}

impl<S, M> K8SpecObj<S, M>
where
    S: Spec,
{
    pub fn new(spec: S, metadata: M) -> Self
    where
        M: Default,
    {
        Self {
            api_version: S::api_version(),
            kind: S::kind(),
            metadata,
            spec,
            ..Default::default()
        }
    }
}

pub type InputK8Obj<S> = K8SpecObj<S, InputObjectMeta>;
pub type UpdateK8Obj<S> = K8SpecObj<S, ItemMeta>;

/// Used for updating k8obj
#[derive(Deserialize, Serialize, Debug, Default, Clone)]
#[serde(rename_all = "camelCase")]
pub struct UpdateK8ObjStatus<S>
where
    S: Spec,
{
    pub api_version: String,
    pub kind: String,
    pub metadata: UpdateItemMeta,
    pub status: S::Status,
    pub data: PhantomData<S>,
}

impl<S> UpdateK8ObjStatus<S>
where
    S: Spec,
{
    pub fn new(status: S::Status, metadata: UpdateItemMeta) -> Self {
        Self {
            api_version: S::api_version(),
            kind: S::kind(),
            metadata,
            status,
            ..Default::default()
        }
    }
}

impl<S> From<UpdateK8Obj<S>> for InputK8Obj<S>
where
    S: Default,
{
    fn from(update: UpdateK8Obj<S>) -> Self {
        Self {
            api_version: update.api_version,
            kind: update.kind,
            metadata: update.metadata.into(),
            spec: update.spec,
            ..Default::default()
        }
    }
}

impl From<ItemMeta> for InputObjectMeta {
    fn from(update: ItemMeta) -> Self {
        Self {
            name: update.name,
            namespace: update.namespace,
            ..Default::default()
        }
    }
}

/// name is optional for template
#[derive(Deserialize, Serialize, Debug, Default, Clone)]
#[serde(rename_all = "camelCase", default)]
pub struct TemplateMeta {
    pub name: Option<String>,
    pub creation_timestamp: Option<String>,
    pub labels: HashMap<String, String>,
}

impl LabelProvider for TemplateMeta {
    fn set_label_map(mut self, labels: HashMap<String, String>) -> Self {
        self.labels = labels;
        self
    }
}

impl TemplateMeta {
    /// create with name and default namespace
    pub fn named<S>(name: S) -> Self
    where
        S: Into<String>,
    {
        Self {
            name: Some(name.into()),
            ..Default::default()
        }
    }
}

#[derive(Deserialize, Serialize, Debug, Default, Clone)]
#[serde(rename_all = "camelCase")]
pub struct TemplateSpec<S> {
    pub metadata: Option<TemplateMeta>,
    pub spec: S,
}

impl<S> TemplateSpec<S> {
    pub fn new(spec: S) -> Self {
        TemplateSpec {
            metadata: None,
            spec,
        }
    }
}

#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
#[serde(bound(serialize = "K8Obj<S>: Serialize"))]
#[serde(bound(deserialize = "K8Obj<S>: DeserializeOwned"))]
pub struct K8List<S>
where
    S: Spec,
{
    pub api_version: String,
    pub kind: String,
    pub metadata: ListMetadata,
    pub items: Vec<K8Obj<S>>,
}

impl<S> K8List<S>
where
    S: Spec,
{
    #[allow(dead_code)]
    pub fn new() -> Self {
        K8List {
            api_version: S::api_version(),
            items: vec![],
            kind: S::kind(),
            metadata: ListMetadata {
                _continue: None,
                resource_version: S::api_version(),
            },
        }
    }
}

impl<S> Default for K8List<S>
where
    S: Spec,
{
    fn default() -> Self {
        Self::new()
    }
}

pub trait DeserializeWith: Sized {
    fn deserialize_with<'de, D>(de: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>;
}

#[derive(Deserialize, Debug, Clone)]
#[serde(tag = "type", content = "object")]
#[serde(bound(serialize = "K8Obj<S>: Serialize"))]
#[serde(bound(deserialize = "K8Obj<S>: DeserializeOwned"))]
pub enum K8Watch<S>
where
    S: Spec,
{
    ADDED(K8Obj<S>),
    MODIFIED(K8Obj<S>),
    DELETED(K8Obj<S>),
}

#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ListMetadata {
    pub _continue: Option<String>,
    pub resource_version: String,
}

#[derive(Deserialize, Serialize, Default, Debug, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct LabelSelector {
    pub match_labels: HashMap<String, String>,
}

impl LabelSelector {
    pub fn new_labels<T: Into<String>>(labels: Vec<(T, T)>) -> Self {
        let mut match_labels = HashMap::new();
        for (key, value) in labels {
            match_labels.insert(key.into(), value.into());
        }
        LabelSelector { match_labels }
    }
}

#[derive(Deserialize, Serialize, Default, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Env {
    pub name: String,
    pub value: Option<String>,
    pub value_from: Option<EnvVarSource>,
}

impl Env {
    pub fn key_value<T: Into<String>>(name: T, value: T) -> Self {
        Env {
            name: name.into(),
            value: Some(value.into()),
            value_from: None,
        }
    }

    pub fn key_field_ref<T: Into<String>>(name: T, field_path: T) -> Self {
        Env {
            name: name.into(),
            value: None,
            value_from: Some(EnvVarSource {
                field_ref: Some(ObjectFieldSelector {
                    field_path: field_path.into(),
                }),
            }),
        }
    }
}

#[derive(Deserialize, Serialize, Default, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct EnvVarSource {
    field_ref: Option<ObjectFieldSelector>,
}

#[derive(Deserialize, Serialize, Default, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ObjectFieldSelector {
    pub field_path: String,
}

#[cfg(test)]
mod test {

    use super::Env;
    use super::ObjectMeta;

    #[test]
    fn test_metadata_label() {
        let metadata =
            ObjectMeta::default().set_labels(vec![("app".to_owned(), "test".to_owned())]);

        let maps = metadata.labels;
        assert_eq!(maps.len(), 1);
        assert_eq!(maps.get("app").unwrap(), "test");
    }

    #[test]
    fn test_env() {
        let env = Env::key_value("lang", "english");
        assert_eq!(env.name, "lang");
        assert_eq!(env.value, Some("english".to_owned()));
    }
}

/*
#[cfg(test)]
mod test_delete {



    use serde_json;
    use serde::{ Serialize,Deserialize};

    use crate::{ Spec,Status, DefaultHeader, Crd, CrdNames};
    use super::DeleteResponse;

    const TEST_API: Crd = Crd {
        group: "test",
        version: "v1",
        names: CrdNames {
            kind: "test",
            plural: "test",
            singular: "test",
        },
    };


    #[derive(Deserialize, Serialize, Default, Debug, Clone)]
    struct TestSpec {}

    impl Spec for TestSpec {
        type Status = TestStatus;
        type Header = DefaultHeader;

        fn metadata() -> &'static Crd {
            &TEST_API
        }
    }

    #[derive(Deserialize, Serialize,Debug, Default,Clone)]
    struct TestStatus(bool);

    impl Status for TestStatus{}

    #[test]
    fn test_deserialize_test_options() {
        let data = r#"
        {
            "kind": "Status",
            "apiVersion": "v1",
            "metadata": {

            },
            "status": "Success",
            "details": {
              "name": "test",
              "group": "test.infinyon.com",
              "kind": "test",
              "uid": "62fc6733-c505-40c1-9dbb-dcd71e93528f"
            }"#;

        // Parse the string of data into serde_json::Value.
        let _status: DeleteResponse<TestSpec> = serde_json::from_str(data).expect("response");
    }
}
*/

/*


impl<'de, S> Deserialize<'de> for DeleteResponse<S>
    where
        S: Spec
{

    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where D: Deserializer<'de>,
    {
        use serde::de::{ Visitor, MapAccess};

        struct StatusVisitor<S: Spec>(PhantomData<fn() -> S>);

        impl<'de,S> Visitor<'de> for StatusVisitor<S>
            where
                S: Spec,
                DeleteResponse<S>: Deserialize<'de>,
        {
            type Value = DeleteResponse<S>;

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

            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                match value {
                    "Success" => Ok(DeleteResponse::OkStatus(StatusEnum::SUCCESS)),
                    "Failure" => Ok(DeleteResponse::OkStatus(StatusEnum::FAILURE)),
                    _ => Err(de::Error::custom(format!("unrecognized status: {}",value)))
                }


            }

            fn visit_map<M>(self, map: M) -> Result<Self::Value, M::Error>
            where
                M: MapAccess<'de>,
            {
                Deserialize::deserialize(de::value::MapAccessDeserializer::new(map))
            }
        }

        deserializer.deserialize_any(StatusVisitor(PhantomData))
    }

}
*/