kube icon indicating copy to clipboard operation
kube copied to clipboard

Add a `DynamicObject::downcast` method

Open clux opened this issue 2 years ago • 5 comments

Would you like to work on this feature?

No response

What problem are you trying to solve?

When dealing with AdmissionReview types we have to deal with DynamicObject inputs and do a manual dance to convert a DynamicObject into one (or more) of the types we created the admission controller for.

I would like to have a quick method to try to convert the input object into one of the actual types.

Describe the solution you'd like

A method or trait impl on DynamicObject to try to convert the DynamicObject into a K.

I don't rust allows an impl<K: Resource> TryFrom<DynamicObject> for K so something like:

  • DynamicObject::try_parse(self) -> Result<K>
  • DynamicObject::downcast(self) -> Result<K>

with some new small error type for the operation.

Describe alternatives you've considered

Trying to parse the DynamicObject::data into a PodSpec, and copying over DynamicObject::types and DynamicObject::metadata into a `Pod.

Documentation, Adoption, Migration Strategy

No response

Target crate for feature

kube-core

clux avatar Sep 26 '22 18:09 clux

Can I work on this?

jmintb avatar Sep 29 '22 06:09 jmintb

Sure, go for it!

clux avatar Sep 29 '22 06:09 clux

I have not been able to find a good way to convert DynamicObject to K: Resource. I have attempted to use a serde based approach serializing the data in DynamicObject and then deserializing into K but this requires K to implement the Deserialize trait. I ran into a few issues here with lifetimes but I think I can get it to work if the Deserialize trait is an acceptable requirement to place on K.

I also tried to downcast using std::any::Any which of course didn't work, as there is no relation between DynamicObject and K except for the shared Resource trait, at least to my knowledge.

Do you have any other ideas for approaching this?

jmintb avatar Oct 10 '22 15:10 jmintb

hm, yeah, I can see that being awkward. Having Serialize and Deserialize requirement on K is not a big deal imo, it's generally always there. That said, you might avoid serialize by taking a shortcut;

  • take the data field
  • extend it with types + metadata
  • pass this single serde_json::Value (with all properties) through serde_json::from_value into K

I think that should work, and would be ok.

clux avatar Oct 11 '22 21:10 clux

Awesome thanks :+1:

jmintb avatar Oct 12 '22 05:10 jmintb

@clux did I miss something on this issue or is it ready to be closed? :)

jmintb avatar Nov 10 '22 16:11 jmintb

Ah, forgot to link it. Thanks!

clux avatar Nov 11 '22 02:11 clux