dora-message 1.2.0

`dora` goal is to be a low latency, composable, and distributed data flow.
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
//! Use these types for integration testing nodes.

use std::{
    collections::{BTreeMap, BTreeSet},
    path::PathBuf,
};

use crate::{
    config::Input,
    descriptor::EnvValue,
    id::{DataId, NodeId},
    metadata::MetadataParameters,
};

/// Defines the input data and events for integration testing a node.
///
/// Most of the fields are similar to the fields defined in the [`Node`](crate::descriptor::Node)
/// struct, which is used to define nodes in a dataflow YAML file.
///
/// For integration testing, the most important field is the [`events`](Self::events) field, which
/// specifies the events that should be sent to the node during the test.
#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct IntegrationTestInput {
    /// Unique node identifier.
    ///
    /// Node IDs may only contain ASCII letters, digits, `_`, `.` and `-`
    /// (no `/`, no whitespace), with the following further limitations:
    ///
    /// - They must not be empty or start with `.`.
    /// - They must not be the reserved id `dora`.
    ///
    /// Each node must have an ID field.
    ///
    /// ## Example
    ///
    /// ```yaml
    /// nodes:
    ///   - id: camera_node
    ///   - id: some_other_node
    /// ```
    pub id: NodeId,

    /// Human-readable node name for documentation.
    ///
    /// This optional field can be used to define a more descriptive name in addition to a short
    /// [`id`](Self::id).
    ///
    /// ## Example
    ///
    /// ```yaml
    /// nodes:
    ///   - id: camera_node
    ///     name: "Camera Input Handler"
    pub name: Option<String>,

    /// Detailed description of the node's functionality.
    ///
    /// ## Example
    ///
    /// ```yaml
    /// nodes:
    ///   - id: camera_node
    ///     description: "Captures video frames from webcam"
    /// ```
    pub description: Option<String>,

    /// Command-line arguments passed to the executable.
    ///
    /// The command-line arguments that should be passed to the executable/script specified in `path`.
    /// The arguments should be separated by space.
    /// This field is optional and defaults to an empty argument list.
    ///
    /// ## Example
    /// ```yaml
    /// nodes:
    ///   - id: example
    ///     path: example-node
    ///     args: -v --some-flag foo
    /// ```
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub args: Option<String>,

    /// Environment variables for node builds and execution.
    ///
    /// Key-value map of environment variables that should be set for both the
    /// [`build`](crate::descriptor::Node::build) operation and the node execution (i.e. when the node is spawned
    /// through [`path`](crate::descriptor::Node::path)).
    ///
    /// Supports strings, numbers, and booleans.
    ///
    /// ## Example
    ///
    /// ```yaml
    /// nodes:
    ///   - id: example-node
    ///     path: path/to/node
    ///     env:
    ///       DEBUG: true
    ///       PORT: 8080
    ///       API_KEY: "secret-key"
    /// ```
    pub env: Option<BTreeMap<String, EnvValue>>,

    /// Output data identifiers produced by this node.
    ///
    /// List of output identifiers that the node sends.
    /// Must contain all `output_id` values that the node uses when sending output, e.g. through the
    /// [`send_output`](https://docs.rs/dora-node-api/latest/dora_node_api/struct.DoraNode.html#method.send_output)
    /// function.
    ///
    /// ## Example
    ///
    /// ```yaml
    /// nodes:
    ///   - id: example-node
    ///     outputs:
    ///       - processed_image
    ///       - metadata
    /// ```
    #[serde(default)]
    pub outputs: BTreeSet<DataId>,

    /// Input data connections from other nodes.
    ///
    /// Defines the inputs that this node is subscribing to.
    ///
    /// The `inputs` field should be a key-value map of the following format:
    ///
    /// `input_id: source_node_id/source_node_output_id`
    ///
    /// The components are defined as follows:
    ///
    ///   - `input_id` is the local identifier that should be used for this input.
    ///
    ///     This will map to the `id` field of
    ///     [`Event::Input`](https://docs.rs/dora-node-api/latest/dora_node_api/enum.Event.html#variant.Input)
    ///     events sent to the node event loop.
    ///   - `source_node_id` should be the `id` field of the node that sends the output that we want
    ///     to subscribe to
    ///   - `source_node_output_id` should be the identifier of the output that that we want
    ///     to subscribe to
    ///
    /// ## Example
    ///
    /// ```yaml
    /// nodes:
    ///   - id: example-node
    ///     outputs:
    ///       - one
    ///       - two
    ///   - id: receiver
    ///     inputs:
    ///         my_input: example-node/two
    /// ```
    #[serde(default)]
    pub inputs: BTreeMap<DataId, Input>,

    /// Redirect stdout/stderr to a data output.
    ///
    /// This field can be used to send all stdout and stderr output of the node as a Dora output.
    /// Each output line is sent as a separate message.
    ///
    ///
    /// ## Example
    ///
    /// ```yaml
    /// nodes:
    ///   - id: example
    ///     send_stdout_as: stdout_output
    ///   - id: logger
    ///     inputs:
    ///         example_output: example/stdout_output
    /// ```
    #[serde(skip_serializing_if = "Option::is_none")]
    pub send_stdout_as: Option<String>,

    /// List of incoming events for the integration test.
    ///
    /// The node event stream will yield these events during the test. Once the list is exhausted,
    /// the event stream will close itself.
    pub events: Vec<TimedIncomingEvent>,

    /// Status of the recording that produced this file. Emitted by the
    /// `DORA_WRITE_EVENTS_TO` recorder; `None` for files produced by
    /// older versions of dora (before #1857) or hand-authored fixtures.
    ///
    /// Consumers should refuse to replay (or at minimum warn loudly)
    /// when this is `Some(RecordingStatus::Poisoned { .. })`, because
    /// the `events` array is incomplete relative to the original run.
    ///
    /// Boxed so the (large) `RecordingStatus::Poisoned` variant doesn't
    /// inflate `IntegrationTestInput`'s size for the common-case
    /// `Clean`-or-`None` recording. This also avoids
    /// `large_enum_variant` lints on `TestingInput::Input(...)` (32
    /// call sites; widening that enum would be intrusive).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub recording_status: Option<Box<RecordingStatus>>,
}

/// State of a `DORA_WRITE_EVENTS_TO` recording (#1857).
///
/// `Clean` means the recorder observed every event it was asked to
/// record. `Poisoned` means at least one `record_event()` call failed
/// (Arrow→JSON conversion error, file I/O error, etc.) — the `events`
/// array is missing at least one event, and replay results will not
/// match the original run.
#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(tag = "state", rename_all = "lowercase")]
pub enum RecordingStatus {
    Clean,
    Poisoned {
        /// Index in the `events` array where the first missed event
        /// would have been. Equals the number of events that WERE
        /// successfully recorded before the first failure.
        first_failure_event_index: usize,
        /// Seconds since the EventStream's start timestamp at the
        /// moment of the first failure.
        first_failure_time_offset_secs: f64,
        /// `format!("{:?}", err)` of the first `record_event()` error.
        first_failure_error: String,
        /// Count of subsequent failures after the first one.
        additional_failures: u64,
    },
}

impl IntegrationTestInput {
    pub fn new(id: NodeId, events: Vec<TimedIncomingEvent>) -> Self {
        Self {
            id,
            name: None,
            description: None,
            args: None,
            env: None,
            outputs: BTreeSet::new(),
            inputs: BTreeMap::new(),
            send_stdout_as: None,
            events,
            recording_status: None,
        }
    }
}

/// An incoming event with a time offset.
#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct TimedIncomingEvent {
    /// The time offset in seconds from the start of the node.
    pub time_offset_secs: f64,
    /// The incoming event.
    #[serde(flatten)]
    pub event: IncomingEvent,
}

/// An event that is sent to a node during an integration test.
///
/// This struct is very similar to the `Event` enum used during normal node operation.
#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(tag = "type")]
pub enum IncomingEvent {
    Stop,
    Input {
        id: DataId,
        metadata: Option<MetadataParameters>,
        /// The input payload, given inline as the keys of [`InputData`].
        ///
        /// Absent when the event carries none of those keys. Keys of
        /// [`InputData`] that do not form a valid value are an error rather
        /// than an input without data.
        #[serde(flatten, deserialize_with = "deserialize_flattened_input_data")]
        data: Option<Box<InputData>>,
    },
    InputClosed {
        id: DataId,
    },
    AllInputsClosed,
}

/// The keys of [`InputData`]'s variants, as they appear flattened into an
/// [`IncomingEvent::Input`].
const INPUT_DATA_KEYS: &[&str] = &["data", "data_type", "path", "batch_index", "column"];

/// Deserializes the flattened `data` of [`IncomingEvent::Input`].
///
/// serde's own handling of a flattened `Option` discards the error of the
/// inner type and yields `None`, so an invalid `batch_index` or a `path`
/// next to a mistyped key would silently turn into an input without a
/// payload. Instead, an event that carries none of the [`InputData`] keys
/// has no data, and one that carries any of them must parse. Other keys
/// are ignored, as they are everywhere else in this format.
fn deserialize_flattened_input_data<'de, D>(
    deserializer: D,
) -> Result<Option<Box<InputData>>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    use serde::{Deserialize, de::Error};

    let mut rest = serde_json::Map::<String, serde_json::Value>::deserialize(deserializer)?;
    rest.retain(|key, _| INPUT_DATA_KEYS.contains(&key.as_str()));
    if rest.is_empty() {
        return Ok(None);
    }
    let keys = rest.keys().cloned().collect::<Vec<_>>();
    InputData::deserialize(serde_json::Value::Object(rest))
        .map(|data| Some(Box::new(data)))
        .map_err(|err| {
            D::Error::custom(format!(
                "invalid input data (keys {keys:?}): expected either `data` \
                 (with optional `data_type`) or `path` (with optional \
                 `batch_index` and `column`): {err}"
            ))
        })
}

/// Represents the data of an incoming input event for integration testing.
#[derive(Debug, PartialEq, Eq, Clone, serde::Deserialize, serde::Serialize)]
#[serde(untagged)]
pub enum InputData {
    /// Converts the given JSON object to the closest Arrow representation.
    ///
    /// An optional data type can be provided to guide the conversion.
    JsonObject {
        /// The input data as JSON.
        ///
        /// This can be a JSON array, object, string, number, boolean, etc. Dora automatically
        /// converts the JSON to an Apache Arrow array, wrapping the data if needed (e.g. wrap
        /// bare integers into an array because Arrow requires all data to be in array form).
        data: serde_json::Value,
        /// Specifies the arrow `DataType` of the `data` field.
        ///
        /// This field is optional. If not set, Dora will try to infer the data type automatically.
        ///
        /// Use this field if the exact data type is important (e.g. to distinguish between
        /// different integer sizes).
        data_type: Option<serde_json::Value>,
    },
    /// Load data from an Arrow IPC file.
    ///
    /// The data must be in the
    /// [Arrow IPC file format](https://arrow.apache.org/docs/python/ipc.html#writing-and-reading-random-access-files)
    ArrowFile {
        /// The path to the Arrow IPC file.
        path: PathBuf,
        /// The optional batch index to read from the file.
        ///
        /// Arrow IPC files can contain multiple record batches. Only one batch is read per input
        /// event. This field specifies which batch to read. Defaults to `0`.
        #[serde(default)]
        batch_index: usize,
        /// Optional column name to read from the record batch.
        ///
        /// If not set, the entire record batch is read and converted to an Arrow `StructArray`.
        column: Option<String>,
    },
}

#[cfg(test)]
mod tests {
    use super::*;

    fn parse_event(json: &str) -> Result<IncomingEvent, serde_json::Error> {
        serde_json::from_str::<TimedIncomingEvent>(json).map(|e| e.event)
    }

    #[test]
    fn input_without_data_keys_has_no_data() {
        let event = parse_event(r#"{"time_offset_secs":0.1,"type":"Input","id":"in"}"#)
            .expect("an input without data is valid");
        assert_eq!(
            event,
            IncomingEvent::Input {
                id: "in".to_owned().into(),
                metadata: None,
                data: None,
            }
        );
    }

    /// [`INPUT_DATA_KEYS`] must name every field of [`InputData`]: a field
    /// missing from it would be filtered out before parsing.
    #[test]
    fn input_data_keys_cover_every_input_data_field() {
        for data in [
            InputData::JsonObject {
                data: serde_json::json!([1]),
                data_type: Some(serde_json::json!("Int32")),
            },
            InputData::ArrowFile {
                path: "x.arrow".into(),
                batch_index: 1,
                column: Some("c".into()),
            },
        ] {
            let serde_json::Value::Object(fields) = serde_json::to_value(&data).unwrap() else {
                panic!("InputData serializes as an object");
            };
            for key in fields.keys() {
                assert!(INPUT_DATA_KEYS.contains(&key.as_str()), "`{key}` missing");
            }
        }
    }

    /// Keys outside [`InputData`] (comments, fields of a newer recorder)
    /// are ignored, as they were before.
    #[test]
    fn input_with_only_unknown_keys_has_no_data() {
        let event =
            parse_event(r#"{"time_offset_secs":0.1,"type":"Input","id":"in","comment":"tick"}"#)
                .expect("unknown keys are ignored");
        assert!(matches!(event, IncomingEvent::Input { data: None, .. }));
    }

    #[test]
    fn input_data_variants_still_parse() {
        let event = parse_event(
            r#"{"time_offset_secs":0,"type":"Input","id":"in","data":[1,2],"metadata":{}}"#,
        )
        .expect("inline JSON data");
        let IncomingEvent::Input { data, metadata, .. } = event else {
            panic!("expected an input, got {event:?}");
        };
        assert!(metadata.is_some());
        assert!(matches!(
            data.as_deref(),
            Some(InputData::JsonObject { .. })
        ));

        let event = parse_event(
            r#"{"time_offset_secs":0,"type":"Input","id":"in","path":"x.arrow","batch_index":2}"#,
        )
        .expect("Arrow file data");
        let IncomingEvent::Input { data, .. } = event else {
            panic!("expected an input, got {event:?}");
        };
        assert_eq!(
            data.as_deref(),
            Some(&InputData::ArrowFile {
                path: "x.arrow".into(),
                batch_index: 2,
                column: None,
            })
        );
    }

    /// serde turns any error inside a flattened `Option` into `None`, so
    /// these used to load as inputs without a payload.
    #[test]
    fn malformed_input_data_is_an_error() {
        for json in [
            r#"{"time_offset_secs":0,"type":"Input","id":"in","path":"x.arrow","batch_index":-1}"#,
            r#"{"time_offset_secs":0,"type":"Input","id":"in","path":"x.arrow","batch_index":"2"}"#,
            // `path` is missing, so the other Arrow file keys match nothing.
            r#"{"time_offset_secs":0,"type":"Input","id":"in","pth":"x.arrow","batch_index":1}"#,
            r#"{"time_offset_secs":0,"type":"Input","id":"in","data_type":"Int32"}"#,
        ] {
            let err = parse_event(json).expect_err(json);
            assert!(
                err.to_string().contains("invalid input data"),
                "{json}: {err}"
            );
        }
    }

    /// Pre-#1857 recordings and hand-authored fixtures have no
    /// `recording_status` field. They must continue to deserialize
    /// cleanly with `recording_status: None`, otherwise the new
    /// schema breaks the entire existing fixture corpus.
    #[test]
    fn integration_test_input_without_recording_status_deserializes() {
        let json = r#"{
            "id": "test-node",
            "events": []
        }"#;
        let v: IntegrationTestInput = serde_json::from_str(json).expect("deserialize legacy form");
        assert!(v.recording_status.is_none());
    }

    /// Clean recordings emit `{"recording_status": {"state": "clean"}}`.
    /// Deserialization should land on `Some(RecordingStatus::Clean)`.
    #[test]
    fn integration_test_input_with_clean_recording_status_deserializes() {
        let json = r#"{
            "id": "test-node",
            "events": [],
            "recording_status": { "state": "clean" }
        }"#;
        let v: IntegrationTestInput = serde_json::from_str(json).expect("deserialize clean form");
        assert_eq!(v.recording_status.as_deref(), Some(&RecordingStatus::Clean));
    }

    /// Poisoned recordings carry the failure details; the deserialized
    /// enum variant must preserve every field. The exact JSON shape
    /// here is what `event_stream::WriteEventsTo::write_out` produces
    /// in dora-node-api — pinning both sides of the wire contract.
    #[test]
    fn integration_test_input_with_poisoned_recording_status_deserializes() {
        let json = r#"{
            "id": "test-node",
            "events": [],
            "recording_status": {
                "state": "poisoned",
                "first_failure_event_index": 7,
                "first_failure_time_offset_secs": 1.25,
                "first_failure_error": "Arrow conversion failed: bad type",
                "additional_failures": 3
            }
        }"#;
        let v: IntegrationTestInput =
            serde_json::from_str(json).expect("deserialize poisoned form");
        match v.recording_status.map(|b| *b) {
            Some(RecordingStatus::Poisoned {
                first_failure_event_index,
                first_failure_time_offset_secs,
                first_failure_error,
                additional_failures,
            }) => {
                assert_eq!(first_failure_event_index, 7);
                assert_eq!(first_failure_time_offset_secs, 1.25);
                assert_eq!(first_failure_error, "Arrow conversion failed: bad type");
                assert_eq!(additional_failures, 3);
            }
            other => panic!("expected Poisoned, got {other:?}"),
        }
    }
}