mx-message 3.1.4

A fast, type-safe Rust implementation of MXMessage for parsing MX messages.
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
# MX Message Dataflow Plugins

This directory contains dataflow-rs plugin implementations for ISO20022 MX message processing. These plugins integrate with the [dataflow-rs](https://github.com/Plasmatic/dataflow-rs) workflow engine to provide a complete message processing pipeline.

## Overview

The MX plugin system provides four core operations for ISO20022 message handling:

1. **Generate** - Create sample MX messages from datafake schemas
2. **Publish** - Convert JSON to ISO20022 XML format
3. **Validate** - Validate XML messages against schemas and business rules
4. **Parse** - Convert XML back to structured JSON

## Parameter Naming Convention

All plugins follow a consistent **source/target** naming pattern:

- **`source`** - The field name containing input data (where data comes from)
- **`target`** - The field name where output will be stored (where data goes to)

This convention:
- ✅ Provides clear semantic meaning
- ✅ Avoids confusion with dataflow-rs `input` configuration object
- ✅ Makes data flow direction explicit in workflows
- ✅ Maintains consistency across all plugins

## Plugin Reference

### 1. Generate Plugin (`generate_mx`)

Generates sample ISO20022 MX messages using datafake scenarios.

**Parameters:**
- `target` (required): Field name where generated JSON data will be stored

**Input:**
- Reads datafake scenario from message payload

**Output:**
- JSON object containing:
  - `json_data`: Complete MX message structure
  - `message_type`: Detected message type (e.g., "pacs.008")

**Example:**
```json
{
  "function": {
    "name": "generate_mx",
    "input": {
      "target": "sample_json"
    }
  }
}
```

**Use Cases:**
- Test data generation
- Schema validation testing
- Sample message creation for documentation

---

### 2. Publish Plugin (`publish_mx`)

Converts JSON MX message data to ISO20022 XML format.

**Parameters:**
- `source` (required): Field name containing JSON message data
- `target` (required): Field name where XML output will be stored

**Input:**
- JSON object with MX message structure (with or without AppHdr envelope)

**Output:**
- ISO20022 compliant XML string

**Example:**
```json
{
  "function": {
    "name": "publish_mx",
    "input": {
      "source": "sample_json",
      "target": "sample_xml"
    }
  }
}
```

**Features:**
- Auto-detects message type from JSON structure
- Supports both Document-only and full envelope (AppHdr + Document) formats
- Generates namespace-compliant XML
- Validates structure during serialization

---

### 3. Validate Plugin (`validate_mx`)

Validates ISO20022 XML messages against schemas and business rules.

**Parameters:**
- `source` (required): Field name containing XML message to validate
- `target` (required): Field name where validation results will be stored

**Input:**
- ISO20022 XML string (with or without AppHdr envelope)

**Output:**
- JSON object with validation results:
  ```json
  {
    "valid": true/false,
    "errors": ["error message 1", "error message 2", ...],
    "warnings": [],
    "timestamp": "2025-10-12T10:30:00Z"
  }
  ```

**Example:**
```json
{
  "function": {
    "name": "validate_mx",
    "input": {
      "source": "sample_xml",
      "target": "validation_result"
    }
  }
}
```

**Validation Checks:**
- XML structure and syntax
- ISO20022 schema compliance
- CBPR+ (Central Bank Payment Regulation Plus) rules
- Field length and pattern constraints
- Business rule validation

---

### 4. Parse Plugin (`parse_mx`)

Parses ISO20022 XML messages into structured JSON format.

**Parameters:**
- `source` (required): Field name containing XML message
- `target` (required): Field name where parsed JSON will be stored

**Input:**
- ISO20022 XML string (with or without AppHdr envelope)

**Output:**
- JSON object with structured message data
- Metadata including message type and format

**Example:**
```json
{
  "function": {
    "name": "parse_mx",
    "input": {
      "source": "sample_xml",
      "target": "mx_json"
    }
  }
}
```

**Features:**
- Auto-detects message type from XML
- Handles both envelope and Document-only formats
- Preserves all message structure and data
- Type-safe parsing with validation

---

## Complete Workflow Example

Here's a complete end-to-end workflow demonstrating all four plugins:

```json
{
  "id": "mx_processing_pipeline",
  "name": "ISO20022 MX Processing Pipeline",
  "description": "Complete message processing with generation, publishing, validation, and parsing",
  "priority": 0,
  "tasks": [
    {
      "id": "step_1_generate",
      "name": "Generate Sample Data",
      "description": "Generate sample MX message from datafake scenario",
      "function": {
        "name": "generate_mx",
        "input": {
          "target": "sample_json"
        }
      }
    },
    {
      "id": "step_2_publish",
      "name": "Publish to XML",
      "description": "Convert JSON to ISO20022 XML format",
      "function": {
        "name": "publish_mx",
        "input": {
          "source": "sample_json",
          "target": "sample_xml"
        }
      }
    },
    {
      "id": "step_3_validate",
      "name": "Validate XML",
      "description": "Validate message against ISO20022 schemas",
      "function": {
        "name": "validate_mx",
        "input": {
          "source": "sample_xml",
          "target": "validation_result"
        }
      }
    },
    {
      "id": "step_4_parse",
      "name": "Parse XML",
      "description": "Parse XML back to structured JSON",
      "function": {
        "name": "parse_mx",
        "input": {
          "source": "sample_xml",
          "target": "mx_json"
        }
      }
    }
  ]
}
```

**Data Flow Visualization:**

```
                    ┌─────────────────┐
                    │  Datafake       │
                    │  Scenario       │
                    │  (Payload)      │
                    └────────┬────────┘
                    ┌─────────────────┐
                    │   generate_mx   │
                    │  target: json   │
                    └────────┬────────┘
                    sample_json (JSON)
                    ┌─────────────────┐
                    │   publish_mx    │
                    │  source: json   │
                    │  target: xml    │
                    └────────┬────────┘
                    sample_xml (XML String)
                    ┌────────┴────────┐
                    │                 │
                    ▼                 ▼
           ┌─────────────────┐ ┌─────────────────┐
           │   validate_mx   │ │    parse_mx     │
           │  source: xml    │ │  source: xml    │
           │  target: result │ │  target: parsed │
           └────────┬────────┘ └────────┬────────┘
                    │                   │
                    ▼                   ▼
          validation_result        mx_json (JSON)
```

## Common Usage Patterns

### Pattern 1: Generate and Publish

Generate test data and convert to XML:

```json
{
  "tasks": [
    {
      "function": {
        "name": "generate_mx",
        "input": {"target": "msg_data"}
      }
    },
    {
      "function": {
        "name": "publish_mx",
        "input": {
          "source": "msg_data",
          "target": "msg_xml"
        }
      }
    }
  ]
}
```

### Pattern 2: Parse and Validate

Parse incoming XML and validate:

```json
{
  "tasks": [
    {
      "function": {
        "name": "parse_mx",
        "input": {
          "source": "incoming_xml",
          "target": "parsed_data"
        }
      }
    },
    {
      "function": {
        "name": "validate_mx",
        "input": {
          "source": "incoming_xml",
          "target": "validation"
        }
      }
    }
  ]
}
```

### Pattern 3: Round-Trip Testing

Test JSON → XML → JSON conversion:

```json
{
  "tasks": [
    {
      "function": {
        "name": "publish_mx",
        "input": {
          "source": "original_json",
          "target": "xml_output"
        }
      }
    },
    {
      "function": {
        "name": "parse_mx",
        "input": {
          "source": "xml_output",
          "target": "parsed_json"
        }
      }
    }
  ]
}
```

## Integration with Dataflow-rs

### Registering Plugins

```rust
use mx_message::plugin::register_mx_functions;
use dataflow_rs::Engine;

// Register all MX plugins
let custom_functions = register_mx_functions()
    .into_iter()
    .collect::<HashMap<_, _>>();

// Create engine with workflows and plugins
let engine = Engine::new(workflows, Some(custom_functions));
```

### Processing Messages

```rust
use dataflow_rs::engine::Message;

// Create message with datafake scenario
let scenario = load_datafake_scenario("pacs.008", "business_payment");
let mut message = Message::from_value(&scenario);

// Process through workflow
let result = engine.process_message(&mut message).await?;

// Access results
let generated_json = message.data().get("sample_json");
let xml_output = message.data().get("sample_xml");
let validation_result = message.data().get("validation_result");
let parsed_json = message.data().get("mx_json");
```

## Error Handling

All plugins return structured errors through the dataflow-rs error system:

```rust
use dataflow_rs::engine::error::{DataflowError, Result};

// Example error types:
// - DataflowError::Validation("'source' parameter is required")
// - DataflowError::Validation("Field 'data' not found in message")
// - DataflowError::Validation("XML parsing error: ...")
// - DataflowError::Validation("JSON serialization error: ...")
```

## Testing

Run the end-to-end test suite:

```bash
# Test all message types and scenarios
cargo test test_mx_workflow_pipeline

# Test specific message type
TEST_MESSAGE_TYPE=pacs.008 cargo test test_mx_workflow_pipeline

# Debug specific scenario
TEST_MESSAGE_TYPE=pacs.008 TEST_SCENARIO=cbpr_business_payment \
  TEST_DEBUG=1 TEST_SAMPLE_COUNT=1 \
  cargo test test_mx_workflow_pipeline -- --nocapture
```

## Architecture

### Module Structure

```
src/plugin/
├── mod.rs           # Plugin registration and exports
├── common.rs        # Shared utilities (message type detection, etc.)
├── generate.rs      # Generate plugin implementation
├── parse.rs         # Parse plugin implementation
├── publish.rs       # Publish plugin implementation
├── validate.rs      # Validate plugin implementation
└── README.md        # This file
```

### Key Design Decisions

1. **Consistent Parameter Naming**: `source`/`target` pattern avoids confusion and improves clarity
2. **Field-based I/O**: Plugins read from and write to message data fields (not direct payload manipulation)
3. **Type Safety**: All operations use strongly-typed structs from generated ISO20022 code
4. **Format Detection**: Automatic message type detection from XML/JSON structure
5. **Error Propagation**: Structured error handling with clear error messages

## Supported Message Types

The plugin system supports all ISO20022 MX message types in this library:

- **pacs** - Payment Clearing and Settlement (pacs.008, pacs.009, pacs.003, pacs.004, pacs.002, pacs.010)
- **pain** - Payment Initiation (pain.001, pain.008)
- **camt** - Cash Management (camt.025, camt.027, camt.029, camt.052, camt.053, camt.054, camt.056, camt.057, camt.060, camt.107, camt.108, camt.109)

See `test_scenarios/` directory for example scenarios for each message type.

## Contributing

When adding new plugins or modifying existing ones:

1. Follow the `source`/`target` parameter naming convention
2. Update this README with new functionality
3. Add comprehensive tests in `tests/end2end.rs`
4. Ensure error messages are clear and actionable
5. Add datafake scenarios for new message types

## License

This plugin system is part of the MXMessage library and follows the same license terms.