Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Resource derive macro #1565

Merged
merged 9 commits into from
Sep 9, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 4 additions & 35 deletions examples/errorbounded_configmap_watcher.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
use std::borrow::Cow;

use futures::prelude::*;
use k8s_openapi::{api::core::v1::Pod, NamespaceResourceScope};
use k8s_openapi::api::core::v1::ConfigMap;
use kube::{
api::{Api, ObjectMeta, ResourceExt},
api::{Api, ObjectMeta},
core::DeserializeGuard,
runtime::{reflector::ObjectRef, watcher, WatchStreamExt},
Client, Resource,
Expand All @@ -13,7 +11,8 @@ use tracing::*;

// Variant of ConfigMap that only accepts ConfigMaps with a CA certificate
// to demonstrate parsing failure
#[derive(Deserialize, Debug, Clone)]
#[derive(Resource, Deserialize, Debug, Clone)]
#[inherit(resource = ConfigMap)]
struct CaConfigMap {
metadata: ObjectMeta,
data: CaConfigMapData,
Expand All @@ -25,36 +24,6 @@ struct CaConfigMapData {
ca_crt: String,
}

// Normally you would derive this, but ConfigMap doesn't follow the standard spec/status pattern
impl Resource for CaConfigMap {
type DynamicType = ();
type Scope = NamespaceResourceScope;

fn kind(&(): &Self::DynamicType) -> Cow<'_, str> {
Cow::Borrowed("ConfigMap")
}

fn group(&(): &Self::DynamicType) -> Cow<'_, str> {
Cow::Borrowed("")
}

fn version(&(): &Self::DynamicType) -> Cow<'_, str> {
Cow::Borrowed("v1")
}

fn plural(&(): &Self::DynamicType) -> Cow<'_, str> {
Cow::Borrowed("configmaps")
}

fn meta(&self) -> &ObjectMeta {
&self.metadata
}

fn meta_mut(&mut self) -> &mut ObjectMeta {
&mut self.metadata
}
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
tracing_subscriber::fmt::init();
Expand Down
47 changes: 47 additions & 0 deletions kube-derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#[macro_use] extern crate quote;

mod custom_resource;
mod resource;

/// A custom derive for kubernetes custom resource definitions.
///
Expand Down Expand Up @@ -308,3 +309,49 @@
pub fn derive_custom_resource(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
custom_resource::derive(proc_macro2::TokenStream::from(input)).into()
}

/// A custom derive for inheriting Resource impl for the type.
///
/// This will generate a [`kube::Resource`] trait implementation, which inherits the specified
/// resources trait implementation.
///
/// Such implementation allows to add strict typing to some typical resources like `Secret` or `ConfigMap`,
/// in cases when implementing CRD is not desirable or it does not fit the use-case.
///
/// This object can be used with [`kube::Api`].
///
/// # Example
///
/// ```rust,no_run
/// use kube::api::ObjectMeta;
/// use k8s_openapi::api::core::v1::ConfigMap;
/// use kube_derive::Resource;
/// use kube::Client;
/// use kube::Api;
/// use serde::Deserialize;
///
/// #[derive(Resource, Clone, Debug, Deserialize)]
/// #[inherit(resource = "ConfigMap")]
/// struct FooMap {
/// metadata: ObjectMeta,
/// data: Option<FooMapSpec>,
/// }
///
/// #[derive(Clone, Debug, Deserialize)]
/// struct FooMapSpec {
/// field: String,
/// }
///
/// let client: Client = todo!();
/// let api: Api<FooMap> = Api::default_namespaced(client);
/// let config_map = api.get("with-field");
/// ```
///
/// The example above will generate:
/// ```
/// // impl kube::Resource for FooMap { .. }
/// ```
#[proc_macro_derive(Resource, attributes(inherit))]
clux marked this conversation as resolved.
Show resolved Hide resolved
pub fn derive_resource_inherit(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
resource::derive(proc_macro2::TokenStream::from(input)).into()

Check warning on line 356 in kube-derive/src/lib.rs

View check run for this annotation

Codecov / codecov/patch

kube-derive/src/lib.rs#L355-L356

Added lines #L355 - L356 were not covered by tests
}
127 changes: 127 additions & 0 deletions kube-derive/src/resource.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
// Generated by darling macros, out of our control
#![allow(clippy::manual_unwrap_or_default)]

use darling::{FromDeriveInput, FromMeta};
use syn::{parse_quote, Data, DeriveInput, Path};

/// Values we can parse from #[kube(attrs)]
#[derive(Debug, FromDeriveInput)]
#[darling(attributes(inherit))]
struct InheritAttrs {
resource: syn::Path,
#[darling(default)]
crates: Crates,
}

#[derive(Debug, FromMeta)]
struct Crates {
#[darling(default = "Self::default_kube_core")]
kube_core: Path,
#[darling(default = "Self::default_k8s_openapi")]
k8s_openapi: Path,
}

// Default is required when the subattribute isn't mentioned at all
// Delegate to darling rather than deriving, so that we can piggyback off the `#[darling(default)]` clauses
impl Default for Crates {
fn default() -> Self {
Self::from_list(&[]).unwrap()
}
}

impl Crates {
fn default_kube_core() -> Path {
parse_quote! { ::kube::core } // by default must work well with people using facade crate
}

fn default_k8s_openapi() -> Path {
parse_quote! { ::k8s_openapi }
}
}

pub(crate) fn derive(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
let derive_input: DeriveInput = match syn::parse2(input) {
Err(err) => return err.to_compile_error(),
Ok(di) => di,

Check warning on line 45 in kube-derive/src/resource.rs

View check run for this annotation

Codecov / codecov/patch

kube-derive/src/resource.rs#L42-L45

Added lines #L42 - L45 were not covered by tests
};
// Limit derive to structs
match derive_input.data {

Check warning on line 48 in kube-derive/src/resource.rs

View check run for this annotation

Codecov / codecov/patch

kube-derive/src/resource.rs#L48

Added line #L48 was not covered by tests
Data::Struct(_) | Data::Enum(_) => {}
_ => {
return syn::Error::new_spanned(&derive_input.ident, r#"Unions can not #[derive(Resource)]"#)

Check warning on line 51 in kube-derive/src/resource.rs

View check run for this annotation

Codecov / codecov/patch

kube-derive/src/resource.rs#L51

Added line #L51 was not covered by tests
.to_compile_error()
}
}
let kube_attrs = match InheritAttrs::from_derive_input(&derive_input) {
Err(err) => return err.write_errors(),
Ok(attrs) => attrs,

Check warning on line 57 in kube-derive/src/resource.rs

View check run for this annotation

Codecov / codecov/patch

kube-derive/src/resource.rs#L55-L57

Added lines #L55 - L57 were not covered by tests
};

let InheritAttrs {
resource,

Check warning on line 61 in kube-derive/src/resource.rs

View check run for this annotation

Codecov / codecov/patch

kube-derive/src/resource.rs#L61

Added line #L61 was not covered by tests
crates: Crates {
kube_core,
k8s_openapi,

Check warning on line 64 in kube-derive/src/resource.rs

View check run for this annotation

Codecov / codecov/patch

kube-derive/src/resource.rs#L63-L64

Added lines #L63 - L64 were not covered by tests
},
..
} = kube_attrs;

let rootident = derive_input.ident;

Check warning on line 69 in kube-derive/src/resource.rs

View check run for this annotation

Codecov / codecov/patch

kube-derive/src/resource.rs#L69

Added line #L69 was not covered by tests

let inherit_resource = quote! {

Check warning on line 71 in kube-derive/src/resource.rs

View check run for this annotation

Codecov / codecov/patch

kube-derive/src/resource.rs#L71

Added line #L71 was not covered by tests
impl #kube_core::Resource for #rootident {
type DynamicType = <#resource as #kube_core::Resource>::DynamicType;
type Scope = <#resource as #kube_core::Resource>::Scope;

fn group(_: &<#resource as #kube_core::Resource>::DynamicType) -> std::borrow::Cow<'_, str> {
#resource::group(&Default::default()).into_owned().into()
}

fn kind(_: &<#resource as #kube_core::Resource>::DynamicType) -> std::borrow::Cow<'_, str> {
#resource::kind(&Default::default()).into_owned().into()
}

fn version(_: &<#resource as #kube_core::Resource>::DynamicType) -> std::borrow::Cow<'_, str> {
#resource::version(&Default::default()).into_owned().into()
}

fn api_version(_: &<#resource as #kube_core::Resource>::DynamicType) -> std::borrow::Cow<'_, str> {
#resource::api_version(&Default::default()).into_owned().into()
}

fn plural(_: &<#resource as #kube_core::Resource>::DynamicType) -> std::borrow::Cow<'_, str> {
#resource::plural(&Default::default()).into_owned().into()
}

fn meta(&self) -> &#k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta {
&self.metadata
}

fn meta_mut(&mut self) -> &mut #k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta {
&mut self.metadata
}
}
};

// Concat output
quote! {

Check warning on line 107 in kube-derive/src/resource.rs

View check run for this annotation

Codecov / codecov/patch

kube-derive/src/resource.rs#L107

Added line #L107 was not covered by tests
#inherit_resource
}
}

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

#[test]
fn test_parse_inherit() {
let input = quote! {
#[derive(Resource)]
#[inherit(resource = "ConfigMap")]
struct Foo { metadata: ObjectMeta }
};

let input = syn::parse2(input).unwrap();
InheritAttrs::from_derive_input(&input).unwrap();
}
}
55 changes: 55 additions & 0 deletions kube-derive/tests/resource.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
use k8s_openapi::{
api::core::v1::{ConfigMap, Secret},
ByteString,
};
use kube::api::ObjectMeta;
use kube_derive::Resource;

#[derive(Resource, Default)]
#[inherit(resource = "ConfigMap")]
clux marked this conversation as resolved.
Show resolved Hide resolved
struct TypedMap {
metadata: ObjectMeta,
data: Option<TypedData>,
}

#[derive(Default)]
struct TypedData {
field: String,
}

#[derive(Resource, Default)]
#[inherit(resource = "Secret")]
struct TypedSecret {
metadata: ObjectMeta,
data: Option<TypedSecretData>,
}

#[derive(Default)]
struct TypedSecretData {
field: ByteString,
}

#[cfg(test)]
mod tests {
use kube::Resource;

use crate::{TypedMap, TypedSecret};

#[test]
fn test_parse_config_map_default() {
TypedMap::default();
assert_eq!(TypedMap::kind(&()), "ConfigMap");
assert_eq!(TypedMap::api_version(&()), "v1");
assert_eq!(TypedMap::group(&()), "");
assert_eq!(TypedMap::plural(&()), "configmaps");
}

#[test]
fn test_parse_secret_default() {
TypedSecret::default();
assert_eq!(TypedSecret::kind(&()), "Secret");
assert_eq!(TypedSecret::api_version(&()), "v1");
assert_eq!(TypedSecret::group(&()), "");
assert_eq!(TypedSecret::plural(&()), "secrets");
}
}
4 changes: 4 additions & 0 deletions kube/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,10 @@ cfg_error! {
#[cfg_attr(docsrs, doc(cfg(feature = "derive")))]
pub use kube_derive::CustomResource;

#[cfg(feature = "derive")]
#[cfg_attr(docsrs, doc(cfg(feature = "derive")))]
pub use kube_derive::Resource;

/// Re-exports from `kube-runtime`
#[cfg(feature = "runtime")]
#[cfg_attr(docsrs, doc(cfg(feature = "runtime")))]
Expand Down
Loading