rustcdc 0.1.4

Embeddable Rust CDC library focused on correctness-first capture primitives
Documentation
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
//! Field mapping transform for copy/rename/set/remove operations.

use async_trait::async_trait;
use serde_json::{Map, Value};

use crate::core::{Error, Event, Result};

use super::Transform;

#[derive(Debug, Clone, Default, PartialEq)]
pub struct FieldMappingConfig {
    /// Copy value from source path to destination path.
    pub copy: Vec<(String, String)>,
    /// Move value from source path to destination path.
    pub rename: Vec<(String, String)>,
    /// Set a literal value at destination path.
    pub set_literals: Vec<(String, Value)>,
    /// Remove a field path.
    pub remove: Vec<String>,
    /// When enabled, missing source/remove paths return an error.
    pub strict: bool,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct PathRule {
    raw: String,
    parts: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct MoveRule {
    from_raw: String,
    to_raw: String,
    from: Vec<String>,
    to: Vec<String>,
}

#[derive(Debug, Clone, PartialEq)]
struct SetRule {
    to_raw: String,
    to: Vec<String>,
    value: Value,
}

#[derive(Debug, Clone, PartialEq)]
pub struct FieldMappingTransform {
    pub config: FieldMappingConfig,
    copy_rules: Vec<MoveRule>,
    rename_rules: Vec<MoveRule>,
    set_rules: Vec<SetRule>,
    remove_rules: Vec<PathRule>,
}

impl FieldMappingTransform {
    pub fn new(config: FieldMappingConfig) -> Result<Self> {
        let copy_rules = config
            .copy
            .iter()
            .map(|(from, to)| {
                Ok(MoveRule {
                    from_raw: from.clone(),
                    to_raw: to.clone(),
                    from: parse_path(from)?,
                    to: parse_path(to)?,
                })
            })
            .collect::<Result<Vec<_>>>()?;

        let rename_rules = config
            .rename
            .iter()
            .map(|(from, to)| {
                Ok(MoveRule {
                    from_raw: from.clone(),
                    to_raw: to.clone(),
                    from: parse_path(from)?,
                    to: parse_path(to)?,
                })
            })
            .collect::<Result<Vec<_>>>()?;

        let set_rules = config
            .set_literals
            .iter()
            .map(|(to, value)| {
                Ok(SetRule {
                    to_raw: to.clone(),
                    to: parse_path(to)?,
                    value: value.clone(),
                })
            })
            .collect::<Result<Vec<_>>>()?;

        let remove_rules = config
            .remove
            .iter()
            .map(|path| {
                Ok(PathRule {
                    raw: path.clone(),
                    parts: parse_path(path)?,
                })
            })
            .collect::<Result<Vec<_>>>()?;

        Ok(Self {
            config,
            copy_rules,
            rename_rules,
            set_rules,
            remove_rules,
        })
    }

    fn apply_payload(&self, payload: &mut Option<Value>) -> Result<()> {
        if payload.is_none() && !self.set_rules.is_empty() {
            *payload = Some(Value::Object(Map::new()));
        }

        let Some(value) = payload else {
            return Ok(());
        };

        if !value.is_object() {
            return Err(Error::TransformError(
                "field_mapping requires object payloads".into(),
            ));
        }

        for rule in &self.copy_rules {
            match get_path(value, &rule.from).cloned() {
                Some(source) => set_path(value, &rule.to, source)?,
                None if self.config.strict => {
                    return Err(Error::TransformError(format!(
                        "field_mapping copy source path missing: {}",
                        rule.from_raw
                    )))
                }
                None => {}
            }
        }

        for rule in &self.rename_rules {
            match remove_path(value, &rule.from) {
                Some(source) => set_path(value, &rule.to, source)?,
                None if self.config.strict => {
                    return Err(Error::TransformError(format!(
                        "field_mapping rename source path missing: {}",
                        rule.from_raw
                    )))
                }
                None => {}
            }
        }

        for rule in &self.set_rules {
            set_path(value, &rule.to, rule.value.clone()).map_err(|error| {
                Error::TransformError(format!(
                    "field_mapping set path {} failed: {error}",
                    rule.to_raw
                ))
            })?;
        }

        for rule in &self.remove_rules {
            let removed = remove_path(value, &rule.parts);
            if removed.is_none() && self.config.strict {
                return Err(Error::TransformError(format!(
                    "field_mapping remove path missing: {}",
                    rule.raw
                )));
            }
        }

        Ok(())
    }
}

#[async_trait]
impl Transform for FieldMappingTransform {
    async fn apply(&self, event: &mut Event) -> Result<bool> {
        self.apply_payload(&mut event.before)?;
        self.apply_payload(&mut event.after)?;
        Ok(true)
    }

    fn name(&self) -> &str {
        "field_mapping"
    }
}

fn parse_path(path: &str) -> Result<Vec<String>> {
    let parts: Vec<String> = path
        .split('.')
        .map(str::trim)
        .filter(|part| !part.is_empty())
        .map(str::to_string)
        .collect();

    if parts.is_empty() {
        return Err(Error::ConfigError(format!(
            "field path must not be empty: {path:?}"
        )));
    }

    Ok(parts)
}

fn get_path<'a>(root: &'a Value, parts: &[String]) -> Option<&'a Value> {
    let mut current = root;
    for part in parts {
        match current {
            Value::Object(object) => {
                current = object.get(part)?;
            }
            _ => return None,
        }
    }
    Some(current)
}

fn set_path(root: &mut Value, parts: &[String], value: Value) -> Result<()> {
    let (last, parents) = parts
        .split_last()
        .ok_or_else(|| Error::ConfigError("path must not be empty".into()))?;

    let mut current = root;
    for part in parents {
        match current {
            Value::Object(object) => {
                if !object.contains_key(part) {
                    object.insert(part.clone(), Value::Object(Map::new()));
                }

                current = object.get_mut(part).ok_or_else(|| {
                    Error::TransformError(format!("failed to access path segment: {part}"))
                })?;

                if !current.is_object() {
                    return Err(Error::TransformError(format!(
                        "path segment is not an object: {part}"
                    )));
                }
            }
            _ => {
                return Err(Error::TransformError(
                    "cannot set nested path on non-object payload".into(),
                ));
            }
        }
    }

    match current {
        Value::Object(object) => {
            object.insert(last.clone(), value);
            Ok(())
        }
        _ => Err(Error::TransformError(
            "cannot set field on non-object payload".into(),
        )),
    }
}

fn remove_path(root: &mut Value, parts: &[String]) -> Option<Value> {
    let (last, parents) = parts.split_last()?;

    let mut current = root;
    for part in parents {
        current = match current {
            Value::Object(object) => object.get_mut(part)?,
            _ => return None,
        };
    }

    match current {
        Value::Object(object) => object.remove(last),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use crate::core::{Event, Operation, SourceMetadata, EVENT_ENVELOPE_VERSION};
    use crate::transform::Transform;

    use super::{FieldMappingConfig, FieldMappingTransform};

    fn event() -> Event {
        Event {
            before: Some(json!({
                "user": {"name": "old", "email": "old@example.com"},
                "legacy": true
            })),
            after: Some(json!({
                "id": 1,
                "user": {"name": "alice", "email": "alice@example.com"},
                "legacy": true
            })),
            op: Operation::Insert,
            source: SourceMetadata {
                source_name: "test".into(),
                offset: "1".into(),
                timestamp: 1,
            },
            ts: 1,
            schema: Some("public".into()),
            table: "users".into(),
            primary_key: Some(vec!["id".into()]),
            snapshot: None,
            transaction: None,
            envelope_version: EVENT_ENVELOPE_VERSION,
        }
    }

    #[tokio::test]
    async fn copy_rule_copies_nested_field() {
        let transform = FieldMappingTransform::new(FieldMappingConfig {
            copy: vec![("user.email".into(), "email".into())],
            ..FieldMappingConfig::default()
        })
        .unwrap();

        let mut event = event();
        assert!(transform.apply(&mut event).await.unwrap());
        assert_eq!(event.after.unwrap()["email"], "alice@example.com");
    }

    #[tokio::test]
    async fn rename_rule_moves_field() {
        let transform = FieldMappingTransform::new(FieldMappingConfig {
            rename: vec![("user.name".into(), "user.full_name".into())],
            ..FieldMappingConfig::default()
        })
        .unwrap();

        let mut event = event();
        assert!(transform.apply(&mut event).await.unwrap());
        let after = event.after.unwrap();
        assert_eq!(after["user"]["full_name"], "alice");
        assert!(after["user"].get("name").is_none());
    }

    #[tokio::test]
    async fn set_literal_creates_missing_path() {
        let transform = FieldMappingTransform::new(FieldMappingConfig {
            set_literals: vec![("meta.source".into(), json!("mysql"))],
            ..FieldMappingConfig::default()
        })
        .unwrap();

        let mut event = event();
        assert!(transform.apply(&mut event).await.unwrap());
        assert_eq!(event.after.unwrap()["meta"]["source"], "mysql");
    }

    #[tokio::test]
    async fn remove_rule_deletes_field() {
        let transform = FieldMappingTransform::new(FieldMappingConfig {
            remove: vec!["legacy".into()],
            ..FieldMappingConfig::default()
        })
        .unwrap();

        let mut event = event();
        assert!(transform.apply(&mut event).await.unwrap());
        assert!(event.after.unwrap().get("legacy").is_none());
    }

    #[tokio::test]
    async fn strict_mode_errors_on_missing_source_or_remove() {
        let transform = FieldMappingTransform::new(FieldMappingConfig {
            copy: vec![("missing".into(), "out".into())],
            strict: true,
            ..FieldMappingConfig::default()
        })
        .unwrap();

        let mut first_event = event();
        assert!(transform.apply(&mut first_event).await.is_err());

        let transform = FieldMappingTransform::new(FieldMappingConfig {
            remove: vec!["missing".into()],
            strict: true,
            ..FieldMappingConfig::default()
        })
        .unwrap();

        let mut second_event = event();
        assert!(transform.apply(&mut second_event).await.is_err());
    }

    #[tokio::test]
    async fn mapping_is_deterministic() {
        let transform = FieldMappingTransform::new(FieldMappingConfig {
            copy: vec![("user.email".into(), "email".into())],
            rename: vec![("user.name".into(), "user.full_name".into())],
            set_literals: vec![("meta.version".into(), json!(1))],
            remove: vec!["legacy".into()],
            strict: true,
        })
        .unwrap();

        let mut first = event();
        let mut second = event();
        assert!(transform.apply(&mut first).await.unwrap());
        assert!(transform.apply(&mut second).await.unwrap());

        assert_eq!(first.after, second.after);
        assert_eq!(first.before, second.before);
    }

    #[test]
    fn invalid_path_is_rejected() {
        let error = FieldMappingTransform::new(FieldMappingConfig {
            copy: vec![("".into(), "dest".into())],
            ..FieldMappingConfig::default()
        });

        assert!(error.is_err());
    }
}