dora_message/integration_testing_format.rs
1//! Use these types for integration testing nodes.
2
3use std::{
4 collections::{BTreeMap, BTreeSet},
5 path::PathBuf,
6};
7
8use crate::{
9 config::Input,
10 descriptor::EnvValue,
11 id::{DataId, NodeId},
12 metadata::MetadataParameters,
13};
14
15/// Defines the input data and events for integration testing a node.
16///
17/// Most of the fields are similar to the fields defined in the [`Node`](crate::descriptor::Node)
18/// struct, which is used to define nodes in a dataflow YAML file.
19///
20/// For integration testing, the most important field is the [`events`](Self::events) field, which
21/// specifies the events that should be sent to the node during the test.
22#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
23pub struct IntegrationTestInput {
24 /// Unique node identifier.
25 ///
26 /// Node IDs may only contain ASCII letters, digits, `_`, `.` and `-`
27 /// (no `/`, no whitespace), with the following further limitations:
28 ///
29 /// - They must not be empty or start with `.`.
30 /// - They must not be the reserved id `dora`.
31 ///
32 /// Each node must have an ID field.
33 ///
34 /// ## Example
35 ///
36 /// ```yaml
37 /// nodes:
38 /// - id: camera_node
39 /// - id: some_other_node
40 /// ```
41 pub id: NodeId,
42
43 /// Human-readable node name for documentation.
44 ///
45 /// This optional field can be used to define a more descriptive name in addition to a short
46 /// [`id`](Self::id).
47 ///
48 /// ## Example
49 ///
50 /// ```yaml
51 /// nodes:
52 /// - id: camera_node
53 /// name: "Camera Input Handler"
54 pub name: Option<String>,
55
56 /// Detailed description of the node's functionality.
57 ///
58 /// ## Example
59 ///
60 /// ```yaml
61 /// nodes:
62 /// - id: camera_node
63 /// description: "Captures video frames from webcam"
64 /// ```
65 pub description: Option<String>,
66
67 /// Command-line arguments passed to the executable.
68 ///
69 /// The command-line arguments that should be passed to the executable/script specified in `path`.
70 /// The arguments should be separated by space.
71 /// This field is optional and defaults to an empty argument list.
72 ///
73 /// ## Example
74 /// ```yaml
75 /// nodes:
76 /// - id: example
77 /// path: example-node
78 /// args: -v --some-flag foo
79 /// ```
80 #[serde(default, skip_serializing_if = "Option::is_none")]
81 pub args: Option<String>,
82
83 /// Environment variables for node builds and execution.
84 ///
85 /// Key-value map of environment variables that should be set for both the
86 /// [`build`](crate::descriptor::Node::build) operation and the node execution (i.e. when the node is spawned
87 /// through [`path`](crate::descriptor::Node::path)).
88 ///
89 /// Supports strings, numbers, and booleans.
90 ///
91 /// ## Example
92 ///
93 /// ```yaml
94 /// nodes:
95 /// - id: example-node
96 /// path: path/to/node
97 /// env:
98 /// DEBUG: true
99 /// PORT: 8080
100 /// API_KEY: "secret-key"
101 /// ```
102 pub env: Option<BTreeMap<String, EnvValue>>,
103
104 /// Output data identifiers produced by this node.
105 ///
106 /// List of output identifiers that the node sends.
107 /// Must contain all `output_id` values that the node uses when sending output, e.g. through the
108 /// [`send_output`](https://docs.rs/dora-node-api/latest/dora_node_api/struct.DoraNode.html#method.send_output)
109 /// function.
110 ///
111 /// ## Example
112 ///
113 /// ```yaml
114 /// nodes:
115 /// - id: example-node
116 /// outputs:
117 /// - processed_image
118 /// - metadata
119 /// ```
120 #[serde(default)]
121 pub outputs: BTreeSet<DataId>,
122
123 /// Input data connections from other nodes.
124 ///
125 /// Defines the inputs that this node is subscribing to.
126 ///
127 /// The `inputs` field should be a key-value map of the following format:
128 ///
129 /// `input_id: source_node_id/source_node_output_id`
130 ///
131 /// The components are defined as follows:
132 ///
133 /// - `input_id` is the local identifier that should be used for this input.
134 ///
135 /// This will map to the `id` field of
136 /// [`Event::Input`](https://docs.rs/dora-node-api/latest/dora_node_api/enum.Event.html#variant.Input)
137 /// events sent to the node event loop.
138 /// - `source_node_id` should be the `id` field of the node that sends the output that we want
139 /// to subscribe to
140 /// - `source_node_output_id` should be the identifier of the output that that we want
141 /// to subscribe to
142 ///
143 /// ## Example
144 ///
145 /// ```yaml
146 /// nodes:
147 /// - id: example-node
148 /// outputs:
149 /// - one
150 /// - two
151 /// - id: receiver
152 /// inputs:
153 /// my_input: example-node/two
154 /// ```
155 #[serde(default)]
156 pub inputs: BTreeMap<DataId, Input>,
157
158 /// Redirect stdout/stderr to a data output.
159 ///
160 /// This field can be used to send all stdout and stderr output of the node as a Dora output.
161 /// Each output line is sent as a separate message.
162 ///
163 ///
164 /// ## Example
165 ///
166 /// ```yaml
167 /// nodes:
168 /// - id: example
169 /// send_stdout_as: stdout_output
170 /// - id: logger
171 /// inputs:
172 /// example_output: example/stdout_output
173 /// ```
174 #[serde(skip_serializing_if = "Option::is_none")]
175 pub send_stdout_as: Option<String>,
176
177 /// List of incoming events for the integration test.
178 ///
179 /// The node event stream will yield these events during the test. Once the list is exhausted,
180 /// the event stream will close itself.
181 pub events: Vec<TimedIncomingEvent>,
182
183 /// Status of the recording that produced this file. Emitted by the
184 /// `DORA_WRITE_EVENTS_TO` recorder; `None` for files produced by
185 /// older versions of dora (before #1857) or hand-authored fixtures.
186 ///
187 /// Consumers should refuse to replay (or at minimum warn loudly)
188 /// when this is `Some(RecordingStatus::Poisoned { .. })`, because
189 /// the `events` array is incomplete relative to the original run.
190 ///
191 /// Boxed so the (large) `RecordingStatus::Poisoned` variant doesn't
192 /// inflate `IntegrationTestInput`'s size for the common-case
193 /// `Clean`-or-`None` recording. This also avoids
194 /// `large_enum_variant` lints on `TestingInput::Input(...)` (32
195 /// call sites; widening that enum would be intrusive).
196 #[serde(default, skip_serializing_if = "Option::is_none")]
197 pub recording_status: Option<Box<RecordingStatus>>,
198}
199
200/// State of a `DORA_WRITE_EVENTS_TO` recording (#1857).
201///
202/// `Clean` means the recorder observed every event it was asked to
203/// record. `Poisoned` means at least one `record_event()` call failed
204/// (Arrow→JSON conversion error, file I/O error, etc.) — the `events`
205/// array is missing at least one event, and replay results will not
206/// match the original run.
207#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
208#[serde(tag = "state", rename_all = "lowercase")]
209pub enum RecordingStatus {
210 Clean,
211 Poisoned {
212 /// Index in the `events` array where the first missed event
213 /// would have been. Equals the number of events that WERE
214 /// successfully recorded before the first failure.
215 first_failure_event_index: usize,
216 /// Seconds since the EventStream's start timestamp at the
217 /// moment of the first failure.
218 first_failure_time_offset_secs: f64,
219 /// `format!("{:?}", err)` of the first `record_event()` error.
220 first_failure_error: String,
221 /// Count of subsequent failures after the first one.
222 additional_failures: u64,
223 },
224}
225
226impl IntegrationTestInput {
227 pub fn new(id: NodeId, events: Vec<TimedIncomingEvent>) -> Self {
228 Self {
229 id,
230 name: None,
231 description: None,
232 args: None,
233 env: None,
234 outputs: BTreeSet::new(),
235 inputs: BTreeMap::new(),
236 send_stdout_as: None,
237 events,
238 recording_status: None,
239 }
240 }
241}
242
243/// An incoming event with a time offset.
244#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
245pub struct TimedIncomingEvent {
246 /// The time offset in seconds from the start of the node.
247 pub time_offset_secs: f64,
248 /// The incoming event.
249 #[serde(flatten)]
250 pub event: IncomingEvent,
251}
252
253/// An event that is sent to a node during an integration test.
254///
255/// This struct is very similar to the `Event` enum used during normal node operation.
256#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
257#[serde(tag = "type")]
258pub enum IncomingEvent {
259 Stop,
260 Input {
261 id: DataId,
262 metadata: Option<MetadataParameters>,
263 /// The input payload, given inline as the keys of [`InputData`].
264 ///
265 /// Absent when the event carries none of those keys. Keys of
266 /// [`InputData`] that do not form a valid value are an error rather
267 /// than an input without data.
268 #[serde(flatten, deserialize_with = "deserialize_flattened_input_data")]
269 data: Option<Box<InputData>>,
270 },
271 InputClosed {
272 id: DataId,
273 },
274 AllInputsClosed,
275}
276
277/// The keys of [`InputData`]'s variants, as they appear flattened into an
278/// [`IncomingEvent::Input`].
279const INPUT_DATA_KEYS: &[&str] = &["data", "data_type", "path", "batch_index", "column"];
280
281/// Deserializes the flattened `data` of [`IncomingEvent::Input`].
282///
283/// serde's own handling of a flattened `Option` discards the error of the
284/// inner type and yields `None`, so an invalid `batch_index` or a `path`
285/// next to a mistyped key would silently turn into an input without a
286/// payload. Instead, an event that carries none of the [`InputData`] keys
287/// has no data, and one that carries any of them must parse. Other keys
288/// are ignored, as they are everywhere else in this format.
289fn deserialize_flattened_input_data<'de, D>(
290 deserializer: D,
291) -> Result<Option<Box<InputData>>, D::Error>
292where
293 D: serde::Deserializer<'de>,
294{
295 use serde::{Deserialize, de::Error};
296
297 let mut rest = serde_json::Map::<String, serde_json::Value>::deserialize(deserializer)?;
298 rest.retain(|key, _| INPUT_DATA_KEYS.contains(&key.as_str()));
299 if rest.is_empty() {
300 return Ok(None);
301 }
302 let keys = rest.keys().cloned().collect::<Vec<_>>();
303 InputData::deserialize(serde_json::Value::Object(rest))
304 .map(|data| Some(Box::new(data)))
305 .map_err(|err| {
306 D::Error::custom(format!(
307 "invalid input data (keys {keys:?}): expected either `data` \
308 (with optional `data_type`) or `path` (with optional \
309 `batch_index` and `column`): {err}"
310 ))
311 })
312}
313
314/// Represents the data of an incoming input event for integration testing.
315#[derive(Debug, PartialEq, Eq, Clone, serde::Deserialize, serde::Serialize)]
316#[serde(untagged)]
317pub enum InputData {
318 /// Converts the given JSON object to the closest Arrow representation.
319 ///
320 /// An optional data type can be provided to guide the conversion.
321 JsonObject {
322 /// The input data as JSON.
323 ///
324 /// This can be a JSON array, object, string, number, boolean, etc. Dora automatically
325 /// converts the JSON to an Apache Arrow array, wrapping the data if needed (e.g. wrap
326 /// bare integers into an array because Arrow requires all data to be in array form).
327 data: serde_json::Value,
328 /// Specifies the arrow `DataType` of the `data` field.
329 ///
330 /// This field is optional. If not set, Dora will try to infer the data type automatically.
331 ///
332 /// Use this field if the exact data type is important (e.g. to distinguish between
333 /// different integer sizes).
334 data_type: Option<serde_json::Value>,
335 },
336 /// Load data from an Arrow IPC file.
337 ///
338 /// The data must be in the
339 /// [Arrow IPC file format](https://arrow.apache.org/docs/python/ipc.html#writing-and-reading-random-access-files)
340 ArrowFile {
341 /// The path to the Arrow IPC file.
342 path: PathBuf,
343 /// The optional batch index to read from the file.
344 ///
345 /// Arrow IPC files can contain multiple record batches. Only one batch is read per input
346 /// event. This field specifies which batch to read. Defaults to `0`.
347 #[serde(default)]
348 batch_index: usize,
349 /// Optional column name to read from the record batch.
350 ///
351 /// If not set, the entire record batch is read and converted to an Arrow `StructArray`.
352 column: Option<String>,
353 },
354}
355
356#[cfg(test)]
357mod tests {
358 use super::*;
359
360 fn parse_event(json: &str) -> Result<IncomingEvent, serde_json::Error> {
361 serde_json::from_str::<TimedIncomingEvent>(json).map(|e| e.event)
362 }
363
364 #[test]
365 fn input_without_data_keys_has_no_data() {
366 let event = parse_event(r#"{"time_offset_secs":0.1,"type":"Input","id":"in"}"#)
367 .expect("an input without data is valid");
368 assert_eq!(
369 event,
370 IncomingEvent::Input {
371 id: "in".to_owned().into(),
372 metadata: None,
373 data: None,
374 }
375 );
376 }
377
378 /// [`INPUT_DATA_KEYS`] must name every field of [`InputData`]: a field
379 /// missing from it would be filtered out before parsing.
380 #[test]
381 fn input_data_keys_cover_every_input_data_field() {
382 for data in [
383 InputData::JsonObject {
384 data: serde_json::json!([1]),
385 data_type: Some(serde_json::json!("Int32")),
386 },
387 InputData::ArrowFile {
388 path: "x.arrow".into(),
389 batch_index: 1,
390 column: Some("c".into()),
391 },
392 ] {
393 let serde_json::Value::Object(fields) = serde_json::to_value(&data).unwrap() else {
394 panic!("InputData serializes as an object");
395 };
396 for key in fields.keys() {
397 assert!(INPUT_DATA_KEYS.contains(&key.as_str()), "`{key}` missing");
398 }
399 }
400 }
401
402 /// Keys outside [`InputData`] (comments, fields of a newer recorder)
403 /// are ignored, as they were before.
404 #[test]
405 fn input_with_only_unknown_keys_has_no_data() {
406 let event =
407 parse_event(r#"{"time_offset_secs":0.1,"type":"Input","id":"in","comment":"tick"}"#)
408 .expect("unknown keys are ignored");
409 assert!(matches!(event, IncomingEvent::Input { data: None, .. }));
410 }
411
412 #[test]
413 fn input_data_variants_still_parse() {
414 let event = parse_event(
415 r#"{"time_offset_secs":0,"type":"Input","id":"in","data":[1,2],"metadata":{}}"#,
416 )
417 .expect("inline JSON data");
418 let IncomingEvent::Input { data, metadata, .. } = event else {
419 panic!("expected an input, got {event:?}");
420 };
421 assert!(metadata.is_some());
422 assert!(matches!(
423 data.as_deref(),
424 Some(InputData::JsonObject { .. })
425 ));
426
427 let event = parse_event(
428 r#"{"time_offset_secs":0,"type":"Input","id":"in","path":"x.arrow","batch_index":2}"#,
429 )
430 .expect("Arrow file data");
431 let IncomingEvent::Input { data, .. } = event else {
432 panic!("expected an input, got {event:?}");
433 };
434 assert_eq!(
435 data.as_deref(),
436 Some(&InputData::ArrowFile {
437 path: "x.arrow".into(),
438 batch_index: 2,
439 column: None,
440 })
441 );
442 }
443
444 /// serde turns any error inside a flattened `Option` into `None`, so
445 /// these used to load as inputs without a payload.
446 #[test]
447 fn malformed_input_data_is_an_error() {
448 for json in [
449 r#"{"time_offset_secs":0,"type":"Input","id":"in","path":"x.arrow","batch_index":-1}"#,
450 r#"{"time_offset_secs":0,"type":"Input","id":"in","path":"x.arrow","batch_index":"2"}"#,
451 // `path` is missing, so the other Arrow file keys match nothing.
452 r#"{"time_offset_secs":0,"type":"Input","id":"in","pth":"x.arrow","batch_index":1}"#,
453 r#"{"time_offset_secs":0,"type":"Input","id":"in","data_type":"Int32"}"#,
454 ] {
455 let err = parse_event(json).expect_err(json);
456 assert!(
457 err.to_string().contains("invalid input data"),
458 "{json}: {err}"
459 );
460 }
461 }
462
463 /// Pre-#1857 recordings and hand-authored fixtures have no
464 /// `recording_status` field. They must continue to deserialize
465 /// cleanly with `recording_status: None`, otherwise the new
466 /// schema breaks the entire existing fixture corpus.
467 #[test]
468 fn integration_test_input_without_recording_status_deserializes() {
469 let json = r#"{
470 "id": "test-node",
471 "events": []
472 }"#;
473 let v: IntegrationTestInput = serde_json::from_str(json).expect("deserialize legacy form");
474 assert!(v.recording_status.is_none());
475 }
476
477 /// Clean recordings emit `{"recording_status": {"state": "clean"}}`.
478 /// Deserialization should land on `Some(RecordingStatus::Clean)`.
479 #[test]
480 fn integration_test_input_with_clean_recording_status_deserializes() {
481 let json = r#"{
482 "id": "test-node",
483 "events": [],
484 "recording_status": { "state": "clean" }
485 }"#;
486 let v: IntegrationTestInput = serde_json::from_str(json).expect("deserialize clean form");
487 assert_eq!(v.recording_status.as_deref(), Some(&RecordingStatus::Clean));
488 }
489
490 /// Poisoned recordings carry the failure details; the deserialized
491 /// enum variant must preserve every field. The exact JSON shape
492 /// here is what `event_stream::WriteEventsTo::write_out` produces
493 /// in dora-node-api — pinning both sides of the wire contract.
494 #[test]
495 fn integration_test_input_with_poisoned_recording_status_deserializes() {
496 let json = r#"{
497 "id": "test-node",
498 "events": [],
499 "recording_status": {
500 "state": "poisoned",
501 "first_failure_event_index": 7,
502 "first_failure_time_offset_secs": 1.25,
503 "first_failure_error": "Arrow conversion failed: bad type",
504 "additional_failures": 3
505 }
506 }"#;
507 let v: IntegrationTestInput =
508 serde_json::from_str(json).expect("deserialize poisoned form");
509 match v.recording_status.map(|b| *b) {
510 Some(RecordingStatus::Poisoned {
511 first_failure_event_index,
512 first_failure_time_offset_secs,
513 first_failure_error,
514 additional_failures,
515 }) => {
516 assert_eq!(first_failure_event_index, 7);
517 assert_eq!(first_failure_time_offset_secs, 1.25);
518 assert_eq!(first_failure_error, "Arrow conversion failed: bad type");
519 assert_eq!(additional_failures, 3);
520 }
521 other => panic!("expected Poisoned, got {other:?}"),
522 }
523 }
524}