|
| 1 | +//! Types for isolating deserialization failures. See [`DeserializeGuard`]. |
| 2 | +
|
| 3 | +use std::{borrow::Cow, fmt::Display}; |
| 4 | + |
| 5 | +use k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta; |
| 6 | +use serde::Deserialize; |
| 7 | +use serde_value::DeserializerError; |
| 8 | + |
| 9 | +use crate::{PartialObjectMeta, Resource}; |
| 10 | + |
| 11 | +/// A wrapper type for K that lets deserializing the parent object succeed, even if the K is invalid. |
| 12 | +/// |
| 13 | +/// For example, this can be used to still access valid objects from an `Api::list` call or `watcher`. |
| 14 | +// We can't implement Deserialize on Result<K, InvalidObject> directly, both because of the orphan rule and because |
| 15 | +// it would conflict with serde's blanket impl on Result<K, E>, even if E isn't Deserialize. |
| 16 | +#[derive(Debug, Clone)] |
| 17 | +pub struct DeserializeGuard<K>(pub Result<K, InvalidObject>); |
| 18 | + |
| 19 | +/// An object that failed to be deserialized by the [`DeserializeGuard`]. |
| 20 | +#[derive(Debug, Clone)] |
| 21 | +pub struct InvalidObject { |
| 22 | + // Should ideally be D::Error, but we don't know what type it has outside of Deserialize::deserialize() |
| 23 | + // It *could* be Box<std::error::Error>, but we don't know that it is Send+Sync |
| 24 | + /// The error message from deserializing the object. |
| 25 | + pub error: String, |
| 26 | + /// The metadata of the invalid object. |
| 27 | + pub metadata: ObjectMeta, |
| 28 | +} |
| 29 | + |
| 30 | +impl Display for InvalidObject { |
| 31 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 32 | + self.error.fmt(f) |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +impl<'de, K> Deserialize<'de> for DeserializeGuard<K> |
| 37 | +where |
| 38 | + K: Deserialize<'de>, |
| 39 | + // Not actually used, but we assume that K is a Kubernetes-style resource with a `metadata` section |
| 40 | + K: Resource, |
| 41 | +{ |
| 42 | + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> |
| 43 | + where |
| 44 | + D: serde::Deserializer<'de>, |
| 45 | + { |
| 46 | + // Deserialize::deserialize consumes the deserializer, and we want to retry parsing as an ObjectMetaContainer |
| 47 | + // if the initial parse fails, so that we can still implement Resource for the error case |
| 48 | + let buffer = serde_value::Value::deserialize(deserializer)?; |
| 49 | + |
| 50 | + // FIXME: can we avoid cloning the whole object? metadata should be enough, and even then we could prune managedFields |
| 51 | + K::deserialize(buffer.clone()) |
| 52 | + .map(Ok) |
| 53 | + .or_else(|err| { |
| 54 | + let PartialObjectMeta { metadata, .. } = |
| 55 | + PartialObjectMeta::<K>::deserialize(buffer).map_err(DeserializerError::into_error)?; |
| 56 | + Ok(Err(InvalidObject { |
| 57 | + error: err.to_string(), |
| 58 | + metadata, |
| 59 | + })) |
| 60 | + }) |
| 61 | + .map(DeserializeGuard) |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +impl<K: Resource> Resource for DeserializeGuard<K> { |
| 66 | + type DynamicType = K::DynamicType; |
| 67 | + type Scope = K::Scope; |
| 68 | + |
| 69 | + fn kind(dt: &Self::DynamicType) -> Cow<str> { |
| 70 | + K::kind(dt) |
| 71 | + } |
| 72 | + |
| 73 | + fn group(dt: &Self::DynamicType) -> Cow<str> { |
| 74 | + K::group(dt) |
| 75 | + } |
| 76 | + |
| 77 | + fn version(dt: &Self::DynamicType) -> Cow<str> { |
| 78 | + K::version(dt) |
| 79 | + } |
| 80 | + |
| 81 | + fn plural(dt: &Self::DynamicType) -> Cow<str> { |
| 82 | + K::plural(dt) |
| 83 | + } |
| 84 | + |
| 85 | + fn meta(&self) -> &ObjectMeta { |
| 86 | + self.0.as_ref().map_or_else(|err| &err.metadata, K::meta) |
| 87 | + } |
| 88 | + |
| 89 | + fn meta_mut(&mut self) -> &mut ObjectMeta { |
| 90 | + self.0.as_mut().map_or_else(|err| &mut err.metadata, K::meta_mut) |
| 91 | + } |
| 92 | +} |
| 93 | + |
| 94 | +#[cfg(test)] |
| 95 | +mod tests { |
| 96 | + use k8s_openapi::api::core::v1::{ConfigMap, Pod}; |
| 97 | + use serde_json::json; |
| 98 | + |
| 99 | + use crate::{DeserializeGuard, Resource}; |
| 100 | + |
| 101 | + #[test] |
| 102 | + fn should_parse_meta_of_invalid_objects() { |
| 103 | + let pod_error = serde_json::from_value::<DeserializeGuard<Pod>>(json!({ |
| 104 | + "metadata": { |
| 105 | + "name": "the-name", |
| 106 | + "namespace": "the-namespace", |
| 107 | + }, |
| 108 | + "spec": { |
| 109 | + "containers": "not-a-list", |
| 110 | + }, |
| 111 | + })) |
| 112 | + .unwrap(); |
| 113 | + assert_eq!(pod_error.meta().name.as_deref(), Some("the-name")); |
| 114 | + assert_eq!(pod_error.meta().namespace.as_deref(), Some("the-namespace")); |
| 115 | + pod_error.0.unwrap_err(); |
| 116 | + } |
| 117 | + |
| 118 | + #[test] |
| 119 | + fn should_allow_valid_objects() { |
| 120 | + let configmap = serde_json::from_value::<DeserializeGuard<ConfigMap>>(json!({ |
| 121 | + "metadata": { |
| 122 | + "name": "the-name", |
| 123 | + "namespace": "the-namespace", |
| 124 | + }, |
| 125 | + "data": { |
| 126 | + "foo": "bar", |
| 127 | + }, |
| 128 | + })) |
| 129 | + .unwrap(); |
| 130 | + assert_eq!(configmap.meta().name.as_deref(), Some("the-name")); |
| 131 | + assert_eq!(configmap.meta().namespace.as_deref(), Some("the-namespace")); |
| 132 | + assert_eq!( |
| 133 | + configmap.0.unwrap().data, |
| 134 | + Some([("foo".to_string(), "bar".to_string())].into()) |
| 135 | + ) |
| 136 | + } |
| 137 | + |
| 138 | + #[test] |
| 139 | + fn should_catch_invalid_objects() { |
| 140 | + serde_json::from_value::<DeserializeGuard<Pod>>(json!({ |
| 141 | + "spec": { |
| 142 | + "containers": "not-a-list" |
| 143 | + } |
| 144 | + })) |
| 145 | + .unwrap() |
| 146 | + .0 |
| 147 | + .unwrap_err(); |
| 148 | + } |
| 149 | +} |
0 commit comments