use std::{
collections::{BTreeMap, BTreeSet},
path::PathBuf,
};
use crate::{
config::Input,
descriptor::EnvValue,
id::{DataId, NodeId},
metadata::MetadataParameters,
};
#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct IntegrationTestInput {
pub id: NodeId,
pub name: Option<String>,
pub description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub args: Option<String>,
pub env: Option<BTreeMap<String, EnvValue>>,
#[serde(default)]
pub outputs: BTreeSet<DataId>,
#[serde(default)]
pub inputs: BTreeMap<DataId, Input>,
#[serde(skip_serializing_if = "Option::is_none")]
pub send_stdout_as: Option<String>,
pub events: Vec<TimedIncomingEvent>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub recording_status: Option<Box<RecordingStatus>>,
}
#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(tag = "state", rename_all = "lowercase")]
pub enum RecordingStatus {
Clean,
Poisoned {
first_failure_event_index: usize,
first_failure_time_offset_secs: f64,
first_failure_error: String,
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,
}
}
}
#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct TimedIncomingEvent {
pub time_offset_secs: f64,
#[serde(flatten)]
pub event: IncomingEvent,
}
#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(tag = "type")]
pub enum IncomingEvent {
Stop,
Input {
id: DataId,
metadata: Option<MetadataParameters>,
#[serde(flatten, deserialize_with = "deserialize_flattened_input_data")]
data: Option<Box<InputData>>,
},
InputClosed {
id: DataId,
},
AllInputsClosed,
}
const INPUT_DATA_KEYS: &[&str] = &["data", "data_type", "path", "batch_index", "column"];
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}"
))
})
}
#[derive(Debug, PartialEq, Eq, Clone, serde::Deserialize, serde::Serialize)]
#[serde(untagged)]
pub enum InputData {
JsonObject {
data: serde_json::Value,
data_type: Option<serde_json::Value>,
},
ArrowFile {
path: PathBuf,
#[serde(default)]
batch_index: usize,
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,
}
);
}
#[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");
}
}
}
#[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,
})
);
}
#[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"}"#,
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}"
);
}
}
#[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());
}
#[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));
}
#[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:?}"),
}
}
}