-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathconfig_overrides.rs
More file actions
331 lines (290 loc) · 10.6 KB
/
Copy pathconfig_overrides.rs
File metadata and controls
331 lines (290 loc) · 10.6 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
//! Building-block types for strategy-based `configOverrides`.
//!
//! Operators declare typed override structs choosing patch strategies per file
//! (e.g. [`JsonConfigOverrides`] for JSON files, [`KeyValueConfigOverrides`] for
//! properties files). The types here are composed by each operator into its
//! CRD-specific `configOverrides` struct.
use std::collections::BTreeMap;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use snafu::{ResultExt, Snafu};
use crate::utils::crds::raw_object_schema;
#[derive(Debug, Snafu)]
pub enum Error {
#[snafu(display("failed to serialize base document to JSON"))]
SerializeBaseDocument { source: serde_json::Error },
#[snafu(display("failed to apply JSON patch (RFC 6902)"))]
ApplyJsonPatch { source: json_patch::PatchError },
#[snafu(display("failed to deserialize JSON patch operation {index} from string"))]
DeserializeJsonPatchOperation {
source: serde_json::Error,
index: usize,
},
}
/// Trait that allows the product config pipeline to extract flat key-value
/// overrides from any `configOverrides` type.
///
/// Typed override structs that have no key-value files can use the default
/// implementation, which returns an empty map.
pub trait KeyValueOverridesProvider {
fn get_key_value_overrides(&self, _file: &str) -> BTreeMap<String, Option<String>> {
BTreeMap::new()
}
}
/// Flat key-value overrides for `*.properties`, Hadoop XML, etc.
///
/// This is backwards-compatible with the existing flat key-value YAML format
/// used by `HashMap<String, String>`.
#[derive(Clone, Debug, Default, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
pub struct KeyValueConfigOverrides {
#[serde(flatten)]
pub overrides: BTreeMap<String, String>,
}
impl KeyValueConfigOverrides {
/// Returns the overrides as a `BTreeMap<String, Option<String>>`, matching
/// the format expected by the product config pipeline.
///
/// This is useful when implementing [`KeyValueOverridesProvider`] for a
/// typed override struct that contains [`KeyValueConfigOverrides`] fields.
pub fn as_product_config_overrides(&self) -> BTreeMap<String, Option<String>> {
self.overrides
.iter()
.map(|(k, v)| (k.clone(), Some(v.clone())))
.collect()
}
}
/// ConfigOverrides that can be applied to a JSON file.
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum JsonConfigOverrides {
/// Can be set to arbitrary YAML content, which is converted to JSON and used as
/// [RFC 7396](https://datatracker.ietf.org/doc/html/rfc7396) JSON merge patch.
#[schemars(schema_with = "raw_object_schema")]
JsonMergePatch(serde_json::Value),
/// List of [RFC 6902](https://datatracker.ietf.org/doc/html/rfc6902) JSON patches.
///
/// Can be used when more flexibility is needed, e.g. to only modify elements
/// in a list based on a condition.
///
/// A patch looks something like
///
/// `{"op": "test", "path": "/0/name", "value": "Andrew"}`
///
/// or
///
/// `{"op": "add", "path": "/0/happy", "value": true}`
JsonPatches(Vec<String>),
/// Override the entire config file with the specified JSON document.
///
/// Please note that you can in-line JSON into YAML as follows:
///
/// ```yaml
/// # ... other YAML content
/// userProvided: {
/// "myString": "test",
/// "myList": ["test"],
/// "myBool": true,
/// "my": {"nested.field.with.dots": 42}
/// }
/// ```
///
/// As an alternative you can also stick to YAML:
///
/// ```yaml
/// # ... other YAML content
/// userProvided:
/// myString: test
/// myList: [test]
/// myBool: true
/// my:
/// nested.field.with.dots: 42
/// ```
#[schemars(schema_with = "raw_object_schema")]
UserProvided(serde_json::Value),
}
impl JsonConfigOverrides {
/// Applies this override to a base JSON document and returns the patched
/// document as a [`serde_json::Value`].
///
/// For [`JsonConfigOverrides::JsonMergePatch`] and
/// [`JsonConfigOverrides::JsonPatches`], the base document is patched
/// according to the respective RFC.
///
/// For [`JsonConfigOverrides::UserProvided`], the base document is ignored
/// entirely and the user-provided string is parsed and returned.
pub fn apply(&self, base: &serde_json::Value) -> Result<serde_json::Value, Error> {
match self {
Self::JsonMergePatch(patch) => {
let mut doc = base.clone();
json_patch::merge(&mut doc, patch);
Ok(doc)
}
Self::JsonPatches(patches) => {
let mut doc = base.clone();
let operations: Vec<json_patch::PatchOperation> = patches
.iter()
.enumerate()
.map(|(index, patch_str)| {
serde_json::from_str(patch_str)
.context(DeserializeJsonPatchOperationSnafu { index })
})
.collect::<Result<Vec<_>, _>>()?;
json_patch::patch(&mut doc, &operations).context(ApplyJsonPatchSnafu)?;
Ok(doc)
}
Self::UserProvided(content) => Ok(content.clone()),
}
}
}
#[cfg(test)]
mod tests {
use rstest::rstest;
use serde_json::json;
use super::*;
use crate::utils::yaml_from_str_singleton_map;
#[test]
fn json_merge_patch_add_and_overwrite_fields() {
let base = json!({
"bundles": {
"authz": {
"polling": {
"min_delay_seconds": 10,
"max_delay_seconds": 20
}
}
}
});
let overrides = JsonConfigOverrides::JsonMergePatch(json!({
"bundles": {
"authz": {
"polling": {
"min_delay_seconds": 3,
"max_delay_seconds": 5
}
}
},
"default_decision": "/http/example/authz/allow"
}));
let result = overrides.apply(&base).expect("merge patch should succeed");
assert_eq!(
result["bundles"]["authz"]["polling"]["min_delay_seconds"],
3
);
assert_eq!(
result["bundles"]["authz"]["polling"]["max_delay_seconds"],
5
);
assert_eq!(result["default_decision"], "/http/example/authz/allow");
}
#[test]
fn json_merge_patch_remove_field_with_null() {
let base = json!({
"keep": "this",
"remove": "this"
});
let overrides = JsonConfigOverrides::JsonMergePatch(json!({
"remove": null
}));
let result = overrides.apply(&base).expect("merge patch should succeed");
assert_eq!(result["keep"], "this");
assert!(result.get("remove").is_none());
}
#[test]
fn json_patch_add_remove_replace() {
let base = json!({
"foo": "bar",
"baz": "qux"
});
let overrides = JsonConfigOverrides::JsonPatches(vec![
r#"{"op": "replace", "path": "/foo", "value": "replaced"}"#.to_owned(),
r#"{"op": "remove", "path": "/baz"}"#.to_owned(),
r#"{"op": "add", "path": "/new_key", "value": "new_value"}"#.to_owned(),
]);
let result = overrides.apply(&base).expect("JSON patch should succeed");
assert_eq!(result["foo"], "replaced");
assert!(result.get("baz").is_none());
assert_eq!(result["new_key"], "new_value");
}
#[test]
fn json_patch_invalid_path_returns_error() {
let base = json!({"foo": "bar"});
let overrides = JsonConfigOverrides::JsonPatches(vec![
r#"{"op": "remove", "path": "/nonexistent"}"#.to_owned(),
]);
let result = overrides.apply(&base);
assert!(
matches!(result.unwrap_err(), Error::ApplyJsonPatch { source } if source.to_string()
== "operation '/0' failed at path '/nonexistent': path is invalid"),
"removing a nonexistent path should fail"
);
}
#[test]
fn json_patch_invalid_operation_returns_error() {
let base = json!({"foo": "bar"});
let overrides = JsonConfigOverrides::JsonPatches(vec![r#"{"not_an_op": true}"#.to_owned()]);
let result = overrides.apply(&base);
assert!(
matches!(result.unwrap_err(), Error::DeserializeJsonPatchOperation { source, index: 0 } if source.to_string()
== "missing field `op` at line 1 column 19"),
"invalid patch operation should return an error"
);
}
#[test]
fn user_provided_ignores_base() {
let base = json!({"foo": "bar"});
let content = json!({"custom": true});
let overrides = JsonConfigOverrides::UserProvided(content);
let result = overrides
.apply(&base)
.expect("user provided should succeed");
assert_eq!(result, json!({"custom": true}));
}
#[test]
fn key_value_config_overrides_as_product_config_overrides() {
let mut overrides = BTreeMap::new();
overrides.insert("key1".to_owned(), "value1".to_owned());
overrides.insert("key2".to_owned(), "value2".to_owned());
let kv = KeyValueConfigOverrides { overrides };
let result = kv.as_product_config_overrides();
assert_eq!(result.len(), 2);
assert_eq!(result.get("key1"), Some(&Some("value1".to_owned())));
assert_eq!(result.get("key2"), Some(&Some("value2".to_owned())));
}
#[rstest]
#[case::inline_json(
r#"
# ... other YAML content
userProvided: {
"myString": "test",
"myList": ["test"],
"myBool": true,
"my": {"nested.field.with.dots": 42}
}
"#
)]
#[case::inline_yaml(
"
# ... other YAML content
userProvided:
myString: test
myList: [test]
myBool: true
my:
nested.field.with.dots: 42
"
)]
fn parse_user_provided_json(#[case] yaml: String) {
let expected = json!({
"myString": "test",
"myList": ["test"],
"myBool": true,
"my": {"nested.field.with.dots": 42}
});
let json_config_overrides: JsonConfigOverrides =
yaml_from_str_singleton_map(&yaml).unwrap();
match json_config_overrides {
JsonConfigOverrides::UserProvided(value) => assert_eq!(value, expected),
_ => panic!("JsonConfigOverrides must be of type UserProvided"),
}
}
}