-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathlib.rs
More file actions
990 lines (977 loc) · 32.9 KB
/
Copy pathlib.rs
File metadata and controls
990 lines (977 loc) · 32.9 KB
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
use darling::{FromMeta, ast::NestedMeta};
#[cfg(doc)]
use kube::core::conversion::ConversionReview;
use proc_macro::TokenStream;
use syn::{Error, Item, spanned::Spanned};
use crate::{attrs::module::ModuleAttributes, codegen::module::Module};
#[cfg(test)]
mod test_utils;
mod attrs;
mod codegen;
mod utils;
/// This macro enables generating versioned structs and enums.
///
/// In this guide, code blocks usually come in pairs. The first code block
/// describes how the macro is used. The second expandable block displays the
/// generated piece of code for explanation purposes. It should be noted, that
/// the exact code can diverge from what is being depicted in this guide. Most
/// code is heavily simplified. For example, `#[automatically_derived]` and
/// `#[allow(deprecated)]` are removed in most examples to reduce visual clutter.
///
/// <div class="warning">
///
/// It is **important** to note that this macro must be placed before any other
/// (derive) macros and attributes. Macros supplied before the versioned macro
/// will be erased, because the original struct, enum or module (container) is
/// erased, and new containers are generated. This ensures that the macros and
/// attributes are applied to the generated versioned instances of the
/// container.
///
/// </div>
///
/// # Version Declarations
///
/// Before any of the fields or variants can be versioned, versions need to be
/// declared at the module level. Each version currently supports two
/// parameters: `name` and the `deprecated` flag. The `name` must be a valid
/// (and supported) format.
///
/// <div class="warning">
///
/// Currently, only [Kubernetes API versions][k8s-version-format] are supported.
/// The macro checks each declared version and reports any error encountered
/// during parsing.
///
/// </div>
///
/// It should be noted that the defined struct always represents the **latest**
/// version, eg: when defining three versions `v1alpha1`, `v1beta1`, and `v1`,
/// the struct will describe the structure of the data in `v1`. This behaviour
/// is especially noticeable in the [`changed()`](#changed-action) action which
/// works "backwards" by describing how a field looked before the current
/// (latest) version.
///
/// TODO: Version declarations should eventually be moved back to containers.
///
/// ```
/// # use stackable_versioned_macros::versioned;
/// #[versioned(version(name = "v1alpha1"))]
/// mod versioned {
/// struct Foo {
/// bar: usize,
/// }
/// }
/// ```
///
/// <details>
/// <summary>Generated code</summary>
///
/// 1. The `#[automatically_derived]` attribute indicates that the following
/// piece of code is automatically generated by a macro instead of being
/// handwritten by a developer. This information is used by cargo and rustc.
/// 2. For each declared version, a new module containing the containers is
/// generated. This enables you to reference the container by versions via
/// `v1alpha1::Foo`.
/// 3. This `use` statement gives the generated containers access to the imports
/// at the top of the file. This is a convenience, because otherwise you
/// would need to prefix used items with `super::`. Additionally, other
/// macros can have trouble using items referred to with `super::`.
///
/// ```ignore
/// #[automatically_derived] // 1
/// mod v1alpha1 { // 2
/// use super::*; // 3
/// pub struct Foo {
/// bar: usize,
/// }
/// }
/// ```
/// </details>
///
/// ## Version Deprecation
///
/// The `deprecated` flag marks the version as deprecated. This currently adds
/// the `#[deprecated]` attribute to the appropriate piece of code. In the
/// future, this will additionally mark the CRD version with `deprecated: true`.
/// See the official docs on [version deprecation][k8s-crd-ver-deprecation].
///
/// ```
/// # use stackable_versioned_macros::versioned;
/// #[versioned(version(name = "v1alpha1", deprecated))]
/// mod versioned {
/// struct Foo {
/// bar: usize,
/// }
/// }
/// ```
///
/// <details>
/// <summary>Generated code</summary>
///
/// 1. The `deprecated` flag will generate a `#[deprecated]` attribute and the
/// note is automatically generated.
///
/// ```ignore
/// #[automatically_derived]
/// #[deprecated = "Version v1alpha1 is deprecated"] // 1
/// mod v1alpha1 {
/// use super::*;
/// pub struct Foo {
/// pub bar: usize,
/// }
/// }
/// ```
/// </details>
///
/// ## Version Sorting
///
/// Additionally, it is ensured that each version is unique. Declaring the same
/// version multiple times will result in an error. Furthermore, declaring the
/// versions out-of-order is prohibited by default. It is possible to opt-out
/// of this check by setting `options(allow_unsorted)`.
///
/// <div class="warning">
///
/// It is **not** recommended to use this setting and instead use sorted versions
/// across all versioned items.
///
/// </div>
///
/// ```
/// # use stackable_versioned_macros::versioned;
/// #[versioned(
/// version(name = "v1beta1"),
/// version(name = "v1alpha1"),
/// options(allow_unsorted)
/// )]
/// mod versioned {
/// struct Foo {
/// bar: usize,
/// }
/// }
/// ```
///
/// # Versioning Module
///
/// The purpose of the macro is to version Kubernetes CustomResourceDefinitions
/// (CRDs). As such, the design and how it works is focused on defining and
/// versioning these CRDs. These CRDs are defined as a top-level struct which
/// can them self contain many sub structs.
///
/// To be able to maximize the visibility on items comprising the CRD, the macro
/// needs to be applied to module blocks. The name of the module can be freely
/// chosen. Throughout this guide, the name `versioned` is used. The module is
/// erased in the generated code. This behaviour can however be
/// [customized](#preserve-module).
///
/// TODO: Mention visibility of module
///
/// ## Preserve Module
///
/// The previous examples completely replaced the `versioned` module with
/// top-level version modules. This is the default behaviour. Preserving the
/// module can however be enabled by setting the `preserve_module` flag.
///
/// ```
/// # use stackable_versioned_macros::versioned;
/// #[versioned(
/// version(name = "v1alpha1"),
/// version(name = "v1"),
/// options(preserve_module)
/// )]
/// mod versioned {
/// struct Foo {
/// bar: usize,
/// }
///
/// struct Bar {
/// baz: String,
/// }
/// }
/// ```
///
/// ## Crate Overrides
///
/// Override the import path of specific crates which is especially useful if
/// the crates are brought into scope through re-exports. The following code
/// block depicts supported overrides and their default values.
///
/// ```
/// # use stackable_versioned_macros::versioned;
/// #[versioned(
/// version(name = "v1alpha1"),
/// version(name = "v1beta1"),
/// crates(
/// versioned = "::stackable_versioned",
/// kube_client = "::kube::client",
/// k8s_openapi = "::k8s_openapi",
/// serde_json = "::serde_json",
/// kube_core = "::kube::core",
/// schemars = "::schemars",
/// serde = "::serde",
/// )
/// )]
/// mod versioned {
/// // ...
/// }
/// ```
///
/// ## Additional Options
///
/// This section contains optional options which influence parts of the code
/// generation.
///
/// ```
/// # use stackable_versioned_macros::versioned;
/// #[versioned(
/// version(name = "v1alpha1"),
/// version(name = "v1beta1"),
/// options(k8s(
/// // Highly experimental conversion tracking. Opting into this feature will
/// // introduce frequent breaking changes.
/// experimental_conversion_tracking,
/// // Enables instrumentation and log events via the tracing crate.
/// enable_tracing,
/// ))
/// )]
/// mod versioned {
/// // ...
/// }
/// ```
///
/// ## Merging Submodules
///
/// Modules defined in the versioned module will be re-emitted. This allows for
/// composition of re-exports to compose easier to use imports for downstream
/// consumers of versioned containers. The following rules apply:
///
/// 1. Only modules named the same like defined versions will be re-emitted.
/// Using modules with invalid names will return an error.
/// 2. Only `use` statements defined in the module will be emitted. Declaring
/// other items will return an error.
///
/// ```
/// # use stackable_versioned_macros::versioned;
/// # mod a {
/// # pub mod v1alpha1 {}
/// # }
/// # mod b {
/// # pub mod v1alpha1 {}
/// # }
/// #[versioned(version(name = "v1alpha1"), version(name = "v1"))]
/// mod versioned {
/// mod v1alpha1 {
/// pub use a::v1alpha1::*;
/// pub use b::v1alpha1::*;
/// }
///
/// struct Foo {
/// bar: usize,
/// }
/// }
/// # fn main() {}
/// ```
///
/// <details>
/// <summary>Expand Generated Code</summary>
///
/// ```ignore
/// mod v1alpha1 {
/// use super::*;
/// pub use a::v1alpha1::*;
/// pub use b::v1alpha1::*;
/// pub struct Foo {
/// pub bar: usize,
/// }
/// }
///
/// mod v1 {
/// use super::*;
/// pub struct Foo {
/// pub bar: usize,
/// }
/// }
/// ```
///
/// </details>
///
/// # CRD Spec Definition
///
/// ## Arguments
///
/// <div class="warning">
///
/// It should be noted that not every `#[kube]` argument is supported or
/// forwarded without changes.
///
/// </div>
///
/// Structs annotated with `#[versioned(crd()]` are treated as top-level CRD
/// spec definitions. This section lists all currently supported arguments.
/// Most of these arguments are directly forwarded to the underlying `#[kube]`
/// attribute. Some arguments are specific to this macro and don't exist in the
/// upstream [`kube`] crate.
///
/// ```
/// # use kube::CustomResource;
/// # use schemars::JsonSchema;
/// # use serde::{Deserialize, Serialize};
/// # use stackable_versioned_macros::versioned;
/// #[versioned(version(name = "v1alpha1"), version(name = "v1beta1"))]
/// mod versioned {
/// #[versioned(crd(
/// // **Required.** Set the group of the CRD, usually the domain of the
/// // company, like `example.com`.
/// group = "example.com",
/// // Override the kind field of the CRD. This defaults to the struct
/// // name (without the `Spec` suffix). Overriding this value will also
/// // influence the names of other generated items, like the status
/// // struct (if used) or the version enum.
/// kind = "CustomKind",
/// // Set the singular name. Defaults to lowercased `kind` value.
/// singular = "...",
/// // Set the plural name. Defaults to inferring from singular.
/// plural = "...",
/// // Indicate that this is a namespaced scoped resource rather than a
/// // cluster scoped resource.
/// namespaced,
/// // Set the specified struct as the status subresource. If conversion
/// // tracking is enabled, this struct will be automatically merged into
/// // the generated tracking status struct.
/// status = "FooStatus",
/// // Set a shortname. This can be specified multiple times.
/// shortname = "..."
/// ))]
/// # #[derive(Clone, Debug, Deserialize, Serialize, CustomResource, JsonSchema)]
/// pub struct FooSpec {
/// #[versioned(deprecated(since = "v1beta1"))]
/// deprecated_bar: usize,
/// baz: bool,
/// }
/// }
/// # #[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)]
/// # pub struct FooStatus {}
/// # fn main() {}
/// ```
///
/// ## Field Actions
///
/// This crate currently supports three different item actions. Items can
/// be added, changed, and deprecated. The macro ensures that these actions
/// adhere to the following set of rules:
///
/// 1. Items cannot be added and deprecated in the same version.
/// 2. Items cannot be added and changed in the same version.
/// 3. Items cannot be changed and deprecated in the same version.
/// 4. Items added in version _a_, renamed _0...n_ times in versions
/// b<sub>1</sub>, ..., b<sub>n</sub> and deprecated in
/// version _c_ must ensure _a < b<sub>1</sub>, ..., b<sub>n</sub> < c_.
/// 5. All item actions must use previously declared versions. Using versions
/// not present at the container level will result in an error.
///
/// For items marked as deprecated, one additional rule applies:
///
/// - Fields must start with the `deprecated_` and variants with the
/// `Deprecated` prefix. This is enforced because Kubernetes doesn't allow
/// removing fields in CRDs entirely. Instead, they should be marked as
/// deprecated. By convention this is done with the `deprecated` prefix.
///
/// ### Added Action
///
/// This action indicates that an item is added in a particular version.
/// Available arguments are:
///
/// - `since` to indicate since which version the item is present.
/// - `default` to customize the default function used to populate the item
/// in auto-generated conversion implementations.
///
/// ```
/// # use stackable_versioned_macros::versioned;
/// #[versioned(version(name = "v1alpha1"), version(name = "v1beta1"))]
/// mod versioned {
/// pub struct Foo {
/// #[versioned(added(since = "v1beta1"))]
/// bar: usize,
/// baz: bool,
/// }
/// }
/// ```
///
/// <details>
/// <summary>Expand Generated Code</summary>
///
/// 1. The field `bar` is not yet present in version `v1alpha1` and is therefore
/// not generated.
/// 2. Now the field `bar` is present and uses `Default::default()` to populate
/// the field during conversion. This function can be customized as shown
/// later in this guide.
///
/// ```ignore
/// pub mod v1alpha1 {
/// use super::*;
/// pub struct Foo { // 1
/// pub baz: bool,
/// }
/// }
///
/// impl From<v1alpha1::Foo> for v1beta1::Foo {
/// fn from(foo: v1alpha1::Foo) -> Self {
/// Self {
/// bar: Default::default(), // 2
/// baz: foo.baz,
/// }
/// }
/// }
///
/// pub mod v1beta1 {
/// use super::*;
/// pub struct Foo {
/// pub bar: usize, // 2
/// pub baz: bool,
/// }
/// }
/// ```
/// </details>
///
/// #### Custom Default Function
///
/// To customize the default function used in the generated conversion
/// implementations the `added` action provides the `default` argument. It
/// expects a path to a function without braces. This path can for example point
/// at free-standing or associated functions.
///
/// ```
/// # use stackable_versioned_macros::versioned;
/// #[versioned(version(name = "v1alpha1"), version(name = "v1beta1"))]
/// mod versioned {
/// pub struct Foo {
/// #[versioned(added(since = "v1beta1", default = "default_bar"))]
/// bar: usize,
/// baz: bool,
/// }
/// }
///
/// fn default_bar() -> usize {
/// 42
/// }
/// ```
///
/// <details>
/// <summary>Expand Generated Code</summary>
///
/// 1. Instead of `Default::default()`, the provided function `default_bar()` is
/// used. It is of course fully type checked and needs to return the expected
/// type (`usize` in this case).
///
/// ```ignore
/// // Snip
///
/// impl From<v1alpha1::Foo> for v1beta1::Foo {
/// fn from(foo: v1alpha1::Foo) -> Self {
/// Self {
/// bar: default_bar(), // 1
/// baz: foo.baz,
/// }
/// }
/// }
///
/// // Snip
/// ```
/// </details>
///
/// ### Changed Action
///
/// This action indicates that an item is changed in a particular version. It
/// combines renames and type changes into a single action. You can choose to
/// change the name, change the type or do both. Available arguments are:
///
/// - `since` to indicate since which version the item is changed.
/// - `from_name` to indicate from which previous name the field is renamed.
/// - `from_type` to indicate from which previous type the field is changed.
/// - `upgrade_with` to provide a custom upgrade function. This argument can
/// only be used in combination with the `from_type` argument. The expected
/// function signature is: `fn (OLD_TYPE) -> NEW_TYPE`. This function must
/// not fail.
/// - `downgrade_with` to provide a custom downgrade function. This argument can
/// only be used in combination with the `from_type` argument. The expected
/// function signature is: `fn (NEW_TYPE) -> OLD_TYPE`. This function must
/// not fail.
/// ```
/// # use stackable_versioned_macros::versioned;
/// #[versioned(version(name = "v1alpha1"), version(name = "v1beta1"))]
/// mod versioned {
/// pub struct Foo {
/// #[versioned(changed(
/// since = "v1beta1",
/// from_name = "prev_bar",
/// from_type = "u16",
/// downgrade_with = usize_to_u16
/// ))]
/// bar: usize,
/// baz: bool,
/// }
/// }
///
/// fn usize_to_u16(input: usize) -> u16 {
/// input.try_into().unwrap()
/// }
/// ```
///
/// <details>
/// <summary>Expand Generated Code</summary>
///
/// 1. In version `v1alpha1` the field is named `prev_bar` and uses a `u16`.
/// 2. In the next version, `v1beta1`, the field is now named `bar` and uses
/// `usize` instead of a `u16`. The conversion implementations transforms the
/// type automatically.
///
/// ```ignore
/// pub mod v1alpha1 {
/// use super::*;
/// pub struct Foo {
/// pub prev_bar: u16, // 1
/// pub baz: bool,
/// }
/// }
///
/// impl From<v1alpha1::Foo> for v1beta1::Foo {
/// fn from(foo: v1alpha1::Foo) -> Self {
/// Self {
/// bar: foo.prev_bar.into(), // 2
/// baz: foo.baz,
/// }
/// }
/// }
///
/// pub mod v1beta1 {
/// use super::*;
/// pub struct Foo {
/// pub bar: usize, // 2
/// pub baz: bool,
/// }
/// }
/// ```
/// </details>
///
/// ### Deprecated Action
///
/// This action indicates that an item is deprecated in a particular version.
/// Deprecated items are not removed. Available arguments are:
///
/// - `since` to indicate since which version the item is deprecated.
/// - `note` to specify an optional deprecation note.
///
/// ```
/// # use stackable_versioned_macros::versioned;
/// #[versioned(version(name = "v1alpha1"), version(name = "v1beta1"))]
/// mod versioned {
/// pub struct Foo {
/// #[versioned(deprecated(since = "v1beta1"))]
/// deprecated_bar: usize,
/// baz: bool,
/// }
/// }
/// ```
///
/// <details>
/// <summary>Expand Generated Code</summary>
///
/// 1. In version `v1alpha1` the field `bar` is not yet deprecated and thus uses
/// the name without the `deprecated_` prefix.
/// 2. In version `v1beta1` the field is deprecated and now includes the
/// `deprecated_` prefix. It also uses the `#[deprecated]` attribute to
/// indicate to Clippy this part of Rust code is deprecated. Therefore, the
/// conversion implementations include `#[allow(deprecated)]` to allow the
/// usage of deprecated items in automatically generated code.
///
/// ```ignore
/// pub mod v1alpha1 {
/// use super::*;
/// pub struct Foo {
/// pub bar: usize, // 1
/// pub baz: bool,
/// }
/// }
///
/// #[allow(deprecated)] // 2
/// impl From<v1alpha1::Foo> for v1beta1::Foo {
/// fn from(foo: v1alpha1::Foo) -> Self {
/// Self {
/// deprecated_bar: foo.bar, // 2
/// baz: foo.baz,
/// }
/// }
/// }
///
/// pub mod v1beta1 {
/// use super::*;
/// pub struct Foo {
/// #[deprecated] // 2
/// pub deprecated_bar: usize,
/// pub baz: bool,
/// }
/// }
/// ```
/// </details>
///
/// ## Additional Arguments
///
/// In addition to the field actions, the following top-level field arguments
/// are available:
///
/// ### Hinting Wrapper Types
///
/// With `#[versioned(hint(...))]` it is possible to give hints to the macro
/// that the field contains a wrapped type. Currently, these following hints
/// are supported:
///
/// - `hint(option)`: Indicates that the field contains an `Option<T>`.
/// - `hint(vec)`: Indicates that the field contains a `Vec<T>`.
///
/// These hints are especially useful for generated conversion functions. With
/// these hints in place, the types are correctly mapped using `Into::into`
/// (assuming the necessary `From` trait methods are implemented on the target
/// types for the conversion to be done correctly).
///
/// ```
/// # use stackable_versioned_macros::versioned;
/// #[versioned(version(name = "v1alpha1"), version(name = "v1beta1"))]
/// mod versioned {
/// pub struct Foo {
/// #[versioned(changed(since = "v1beta1", from_type = "Vec<usize>"), hint(vec))]
/// bar: Vec<usize>,
/// baz: bool,
/// }
/// }
/// ```
///
/// # Generated Helpers
///
/// This macro generates a few different helpers to enable different operations
/// around CRD versioning and conversion. The following sections explain these
/// helpers and (some) of the code behind them in detail.
///
/// All these helpers are generated as associated functions on what this macro
/// calls an entry enum. When defining the following three versions: `v1alpha1`,
/// `v1beta1`, and `v1` the following entry enum will be generated:
///
/// ```ignore
/// pub enum Foo {
/// V1Alpha1(v1alpha1::Foo),
/// V1Beta1(v1beta1::Foo),
/// V1(v1::Foo),
/// }
/// ```
///
/// ## Merge CRD Versions
///
/// The generated `merged_crd` method is a wrapper around [kube's `merge_crds`][2]
/// function. It automatically calls the `crd` methods of the CRD in all of its
/// versions and additionally provides a strongly typed selector for the stored
/// API version.
///
/// ```
/// # use stackable_versioned_macros::versioned;
/// # use kube::CustomResource;
/// # use schemars::JsonSchema;
/// # use serde::{Deserialize, Serialize};
/// #[versioned(version(name = "v1alpha1"), version(name = "v1beta1"))]
/// mod versioned {
/// #[versioned(crd(group = "example.com"))]
/// #[derive(Clone, Debug, Deserialize, Serialize, CustomResource, JsonSchema)]
/// pub struct FooSpec {
/// #[versioned(added(since = "v1beta1"))]
/// bar: usize,
/// baz: bool,
/// }
/// }
///
/// # fn main() {
/// let merged_crd = Foo::merged_crd(FooVersion::V1Beta1).unwrap();
/// println!("{yaml}", yaml = serde_yaml::to_string(&merged_crd).unwrap());
/// # }
/// ```
///
/// The strongly typed version enum looks very similar to the entry enum
/// described above. It additionally provides various associated functions used
/// for parsing and string representations.
///
/// ```
/// #[derive(Copy, Clone, Debug)]
/// pub enum FooVersion {
/// V1Alpha1,
/// V1Beta1,
/// }
/// ```
///
/// ---
///
/// The generation of merging helpers can be skipped if manual implementation
/// is desired. The following piece of code lists all possible locations where
/// this skip flag can be provided.
///
/// ```
/// # use stackable_versioned_macros::versioned;
/// # use kube::CustomResource;
/// # use schemars::JsonSchema;
/// # use serde::{Deserialize, Serialize};
/// #
/// # #[versioned(version(name = "v1alpha1"))]
/// #[versioned(skip(merged_crd))] // Skip generation for ALL specs
/// mod versioned {
/// #[versioned(skip(merged_crd))] // Skip generation for specific specs
///
/// # #[versioned(crd(group = "example.com"))]
/// # #[derive(Clone, Debug, CustomResource, Deserialize, Serialize, JsonSchema)]
/// pub struct FooSpec {}
/// }
/// #
/// # fn main() {}
/// ```
///
/// ## Convert CustomResources
///
/// The conversion of CRs is tightly integrated with [`ConversionReview`]s, the
/// payload which a conversion webhook receives from the Kubernetes apiserver.
/// Naturally, the `try_convert` function takes in [`ConversionReview`] as a
/// parameter and also returns a [`ConversionReview`] indicating success or
/// failure.
///
/// ```ignore
/// # use stackable_versioned_macros::versioned;
/// # use kube::CustomResource;
/// # use schemars::JsonSchema;
/// # use serde::{Deserialize, Serialize};
/// #[versioned(
/// version(name = "v1alpha1"),
/// version(name = "v1beta1"),
/// version(name = "v1")
/// )]
/// mod versioned {
/// #[versioned(crd(group = "example.com"))]
/// #[derive(Clone, Debug, Deserialize, Serialize, CustomResource, JsonSchema)]
/// pub struct FooSpec {
/// #[versioned(added(since = "v1beta1"))]
/// bar: usize,
///
/// #[versioned(added(since = "v1"))]
/// baz: bool,
///
/// quox: String,
/// }
/// }
///
/// # fn main() {
/// let conversion_review = Foo::try_convert(conversion_review);
/// # }
/// ```
///
/// The generation of conversion helpers can be skipped if manual implementation
/// is desired. The following piece of code lists all possible locations where
/// this skip flag can be provided:
///
/// ```
/// # use stackable_versioned_macros::versioned;
/// # use kube::CustomResource;
/// # use schemars::JsonSchema;
/// # use serde::{Deserialize, Serialize};
/// #
/// # #[versioned(version(name = "v1alpha1"))]
/// #[versioned(skip(try_convert))] // Skip generation for ALL specs
/// mod versioned {
/// #[versioned(skip(try_convert))] // Skip generation for specific specs
///
/// # #[versioned(crd(group = "example.com"))]
/// # #[derive(Clone, Debug, CustomResource, Deserialize, Serialize, JsonSchema)]
/// pub struct FooSpec {}
/// }
/// #
/// # fn main() {}
/// ```
///
/// ### Conversion Tracking
///
/// <div class="warning">
///
/// This is a highly experimental feature. To enable it, provide the
/// `experimental_conversion_tracking` flag. See the
/// [additional options](#additional-options) section for more information.
///
/// </div>
///
/// As per recommendation by the Kubernetes project, conversions should aim to
/// be infallible and lossless. The above example perfectly illustrates that
/// achieving this is not as easy as it looks on the surface. Let's assume the
/// following conditions:
///
/// - The CRD's latest version `v1` is marked as the stored version.
/// - A client requests a CR in an earlier version, in this case `v1alpha1`.
///
/// The Kubernetes apiserver retrieves the stored object in `v1` from etcd.
/// It needs to be downgraded to `v1alpha1` to be able to serve the client the
/// correct requested version. As defined above, the field `baz` was only added
/// in `v1` and `bar` was added in `v1beta1` and as such both don't exist in
/// `v1alpha1`. During the downgrade, the conversion would lose these pieces of
/// data when upgrading to `v1` again after the client did it's changes. This
/// macro however provides a mechanism to automatically track values across
/// conversations without data loss.
///
/// <div class="warning">
///
/// Currently, only tracking of **added** fields is supported. This will be
/// expanded to removed fields, field type changes, and fields containing
/// collections in the future.
///
/// </div>
///
/// There are many moving parts to enable this mechanism to work automatically
/// with minimal manual developer input. Pretty much all of the required code
/// can be generated based on a simple CRD definition described above. The
/// following paragraphs explain various parts of the system in more detail.
/// For a complete overview, it is however advised to look at the source code
/// of the macro and the code it produces.
///
/// #### Tracking Values in the Status
///
/// Tracking changed values across conversions requires state. In this context,
/// storing this state as close to the CustomResource as possible is essential.
/// This is due to various factors such as avoiding external calls (which are
/// susceptible to network errors), reducing the risk of state drift, and
/// making the use of conversions as easy as possible straight out of the box;
/// for both users and cluster administrators.
///
/// As such, values are tracked using the CustomResource's status via the
/// `changedValues` field. This field contains two sections, one for upgrades
/// and one for downgrades. Both of these sections contain version keys which
/// list all tracked values for a particular version.
///
/// ```yaml
/// status:
/// changedValues:
/// downgrades: null
/// upgrades:
/// v1beta1:
/// - fieldName: "bar"
/// value: 42
/// v1:
/// - fieldName: "baz"
/// value: true
/// ```
///
/// To continue the above example, upgrading the CustomResource from `v1alpha1`
/// back to `v1` requires us to re-hydrate the resource with the tracked values.
/// First, the resource is upgraded to `v1beta1`. During this step, the tracked
/// value for the `bar` field is applied and removed from the status afterwards.
/// The final upgrade to `v1` will apply the tracked value for the field `baz`.
/// Again, it is removed from the status afterwards.
///
/// ### Tracking Nested Changes
///
/// To be able to automatically track values of changed fields in nested sub
/// structs of specs, the fields needs to be marked with `#[versioned(nested)]`.
/// This will indicate the macro to generate the appropriate conversion
/// functions.
///
/// ```
/// # use stackable_versioned_macros::versioned;
/// # use kube::CustomResource;
/// # use schemars::JsonSchema;
/// # use serde::{Deserialize, Serialize};
/// #[versioned(
/// version(name = "v1alpha1"),
/// version(name = "v1beta1"),
/// options(k8s(experimental_conversion_tracking))
/// )]
/// mod versioned {
/// #[versioned(crd(group = "example.com"))]
/// #[derive(Clone, Debug, Deserialize, Serialize, CustomResource, JsonSchema)]
/// struct FooSpec {
/// bar: usize,
///
/// // TODO: This technically needs to be combined with a change, but
/// // we want proper, per-container versioning before we add the correct
/// // attributes here.
/// #[versioned(nested)]
/// baz: Baz,
/// }
///
/// #[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)]
/// struct Baz {
/// quax: String,
///
/// #[versioned(added(since = "v1beta1"))]
/// quox: bool,
/// }
/// }
/// # fn main() {}
/// ```
///
/// # OpenTelemetry Semantic Conventions
///
/// If tracing is enabled, various traces and events are emitted. The fields of
/// these signals follow the general rules of OpenTelemetry semantic conventions.
/// There are currently no agreed-upon semantic conventions for CRD conversions.
/// In the meantime these fields are used:
///
/// | Field | Type (Example) | Description |
/// | :---- | :------------- | :---------- |
/// | `k8s.crd.conversion.converted_object_count` | usize (6) | The number of successfully converted objects sent back in a conversion review |
/// | `k8s.crd.conversion.desired_api_version` | String (v1alpha1) | The desired api version received via a conversion review |
/// | `k8s.crd.conversion.api_version` | String (v1beta1) | The current api version of an object received via a conversion review |
/// | `k8s.crd.conversion.steps` | usize (2) | The number of steps required to convert a single object from the current to the desired version |
/// | `k8s.crd.conversion.kind` | String (Foo) | The kind of the CRD |
///
/// [1]: https://docs.rs/schemars/latest/schemars/derive.JsonSchema.html
/// [2]: https://docs.rs/kube/latest/kube/core/crd/fn.merge_crds.html
/// [k8s-version-format]: https://kubernetes.io/docs/reference/using-api/#api-versioning
/// [k8s-crd-ver-deprecation]: https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definition-versioning/#version-deprecation
#[proc_macro_attribute]
pub fn versioned(attrs: TokenStream, input: TokenStream) -> TokenStream {
let input = syn::parse_macro_input!(input as Item);
versioned_impl(attrs.into(), input).into()
}
fn versioned_impl(attrs: proc_macro2::TokenStream, input: Item) -> proc_macro2::TokenStream {
// TODO (@Techassi): Think about how we can handle nested structs / enums which
// are also versioned.
match input {
Item::Mod(item_mod) => {
let module_attributes: ModuleAttributes = match parse_outer_attributes(attrs) {
Ok(ma) => ma,
Err(err) => return err.write_errors(),
};
let module = match Module::new(item_mod, module_attributes) {
Ok(module) => module,
Err(err) => return err.write_errors(),
};
module.generate_tokens()
}
_ => Error::new(
input.span(),
"attribute macro `versioned` can be only be applied to modules",
)
.into_compile_error(),
}
}
fn parse_outer_attributes<T>(attrs: proc_macro2::TokenStream) -> Result<T, darling::Error>
where
T: FromMeta,
{
let nm = NestedMeta::parse_meta_list(attrs)?;
T::from_list(&nm)
}
#[cfg(test)]
mod snapshots {
use insta::{assert_snapshot, glob};
use super::*;
#[test]
fn pass() {
// TODO (@Techassi): Re-add skip tests
let _settings_guard = test_utils::set_snapshot_path().bind_to_scope();
glob!("../tests/inputs/pass", "*.rs", |path| {
let formatted = test_utils::expand_from_file(path)
.inspect_err(|err| eprintln!("{err}"))
.unwrap();
assert_snapshot!(formatted);
});
}
}