use core::fmt;
use astrs_time::HlcTimestamp;
use oxicode::{Decode, Encode};
use serde::{Deserialize, Serialize};
use crate::common::duration::DurationMs;
use crate::common::node::{InputSpec, NodeSpawnSpec};
use crate::frame::FrameKind;
use crate::handshake::messages::Hello;
use crate::ids::{BuildId, DataId, DataflowId, NodeId, ParamKey, PortRef, SubscriptionId};
use crate::messages::control::types::{
DataflowSource, LogQuery, ParamScope, RequestScope, TopicQuery,
};
use crate::messages::impl_wire_message;
use crate::metadata::{Metadata, Parameter};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Encode, Decode)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ControlRequest {
#[oxicode(variant = 0)]
Hello(Hello),
#[oxicode(variant = 1)]
Build {
manifest: String,
working_dir: Option<String>,
name: Option<String>,
force: bool,
},
#[oxicode(variant = 2)]
WaitForBuild {
build: BuildId,
timeout: Option<DurationMs>,
},
#[oxicode(variant = 3)]
Start {
source: DataflowSource,
name: Option<String>,
detach: bool,
},
#[oxicode(variant = 4)]
WaitForSpawn {
dataflow: DataflowId,
timeout: Option<DurationMs>,
},
#[oxicode(variant = 5)]
Check {
dataflow: Option<DataflowId>,
},
#[oxicode(variant = 6)]
Stop {
dataflow: DataflowId,
grace: Option<DurationMs>,
},
#[oxicode(variant = 7)]
StopByName {
name: String,
grace: Option<DurationMs>,
},
#[oxicode(variant = 8)]
Restart {
dataflow: DataflowId,
rebuild: bool,
},
#[oxicode(variant = 9)]
RestartByName {
name: String,
rebuild: bool,
},
#[oxicode(variant = 10)]
Logs {
dataflow: DataflowId,
node: Option<NodeId>,
query: LogQuery,
},
#[oxicode(variant = 11)]
LogSubscribe {
dataflow: Option<DataflowId>,
node: Option<NodeId>,
query: LogQuery,
subscription: SubscriptionId,
},
#[oxicode(variant = 12)]
List {
all: bool,
},
#[oxicode(variant = 13)]
Info {
dataflow: DataflowId,
include_nodes: bool,
},
#[oxicode(variant = 14)]
Destroy {
force: bool,
},
#[oxicode(variant = 15)]
Clean {
dataflow: Option<DataflowId>,
artifacts: bool,
logs: bool,
},
#[oxicode(variant = 16)]
ConnectedDaemons {
include_unreachable: bool,
},
#[oxicode(variant = 17)]
GetNodeInfo {
dataflow: DataflowId,
node: NodeId,
},
#[oxicode(variant = 18)]
TopicSubscribe {
dataflow: DataflowId,
port: PortRef,
query: TopicQuery,
subscription: SubscriptionId,
},
#[oxicode(variant = 19)]
TopicUnsubscribe {
subscription: SubscriptionId,
},
#[oxicode(variant = 20)]
TopicPublish {
dataflow: DataflowId,
port: PortRef,
metadata: Metadata,
payload: Vec<u8>,
},
#[oxicode(variant = 21)]
GetParams {
scope: ParamScope,
prefix: Option<String>,
inherited: bool,
},
#[oxicode(variant = 22)]
GetParam {
scope: ParamScope,
key: ParamKey,
inherited: bool,
},
#[oxicode(variant = 23)]
SetParam {
scope: ParamScope,
key: ParamKey,
value: Parameter,
create_only: bool,
},
#[oxicode(variant = 24)]
DeleteParam {
scope: ParamScope,
key: ParamKey,
},
#[oxicode(variant = 25)]
RestartNode {
dataflow: DataflowId,
node: NodeId,
},
#[oxicode(variant = 26)]
StopNode {
dataflow: DataflowId,
node: NodeId,
grace: Option<DurationMs>,
},
#[oxicode(variant = 27)]
AddNode {
dataflow: DataflowId,
node: Box<NodeSpawnSpec>,
start: bool,
},
#[oxicode(variant = 28)]
RemoveNode {
dataflow: DataflowId,
node: NodeId,
grace: Option<DurationMs>,
},
#[oxicode(variant = 29)]
ReplaceNode {
dataflow: DataflowId,
node: Box<NodeSpawnSpec>,
drain: bool,
},
#[oxicode(variant = 30)]
AddEdge {
dataflow: DataflowId,
consumer: NodeId,
input: InputSpec,
},
#[oxicode(variant = 31)]
RemoveEdge {
dataflow: DataflowId,
consumer: NodeId,
input: DataId,
},
#[oxicode(variant = 32)]
RecordStart {
dataflow: DataflowId,
path: String,
ports: Vec<PortRef>,
overwrite: bool,
},
#[oxicode(variant = 33)]
RecordStop {
dataflow: DataflowId,
},
#[oxicode(variant = 34)]
GetTraces {
dataflow: Option<DataflowId>,
node: Option<NodeId>,
since: Option<HlcTimestamp>,
limit: Option<u32>,
},
#[oxicode(variant = 35)]
GetNodeMetrics {
dataflow: DataflowId,
node: Option<NodeId>,
},
#[oxicode(variant = 36)]
GetManifest {
dataflow: DataflowId,
},
#[oxicode(variant = 37)]
GetNodeIoMetrics {
dataflow: DataflowId,
node: Option<NodeId>,
},
}
impl ControlRequest {
#[must_use]
pub const fn scope(&self) -> RequestScope {
match self {
Self::Check { .. }
| Self::Logs { .. }
| Self::LogSubscribe { .. }
| Self::List { .. }
| Self::Info { .. }
| Self::ConnectedDaemons { .. }
| Self::GetNodeInfo { .. }
| Self::GetNodeIoMetrics { .. }
| Self::TopicSubscribe { .. }
| Self::TopicUnsubscribe { .. }
| Self::GetParams { .. }
| Self::GetParam { .. }
| Self::GetTraces { .. }
| Self::GetNodeMetrics { .. }
| Self::GetManifest { .. }
| Self::WaitForBuild { .. }
| Self::WaitForSpawn { .. } => RequestScope::Read,
Self::Hello(_) => RequestScope::Read,
Self::Build { .. }
| Self::Start { .. }
| Self::Stop { .. }
| Self::StopByName { .. }
| Self::Restart { .. }
| Self::RestartByName { .. }
| Self::Destroy { .. }
| Self::Clean { .. }
| Self::TopicPublish { .. }
| Self::SetParam { .. }
| Self::DeleteParam { .. }
| Self::RestartNode { .. }
| Self::StopNode { .. }
| Self::AddNode { .. }
| Self::RemoveNode { .. }
| Self::ReplaceNode { .. }
| Self::AddEdge { .. }
| Self::RemoveEdge { .. }
| Self::RecordStart { .. }
| Self::RecordStop { .. } => RequestScope::Mutate,
}
}
#[must_use]
pub const fn is_mutating(&self) -> bool {
self.scope().is_mutating()
}
#[must_use]
pub const fn is_read_only(&self) -> bool {
!self.is_mutating()
}
#[must_use]
pub const fn is_handshake(&self) -> bool {
matches!(self, Self::Hello(_))
}
#[must_use]
pub const fn hello(&self) -> Option<&Hello> {
match self {
Self::Hello(hello) => Some(hello),
_ => None,
}
}
#[must_use]
pub fn dataflow(&self) -> Option<DataflowId> {
match self {
Self::WaitForSpawn { dataflow, .. }
| Self::Stop { dataflow, .. }
| Self::Restart { dataflow, .. }
| Self::Logs { dataflow, .. }
| Self::Info { dataflow, .. }
| Self::GetNodeInfo { dataflow, .. }
| Self::GetNodeMetrics { dataflow, .. }
| Self::GetNodeIoMetrics { dataflow, .. }
| Self::GetManifest { dataflow }
| Self::TopicSubscribe { dataflow, .. }
| Self::TopicPublish { dataflow, .. }
| Self::RestartNode { dataflow, .. }
| Self::StopNode { dataflow, .. }
| Self::AddNode { dataflow, .. }
| Self::RemoveNode { dataflow, .. }
| Self::ReplaceNode { dataflow, .. }
| Self::AddEdge { dataflow, .. }
| Self::RemoveEdge { dataflow, .. }
| Self::RecordStart { dataflow, .. }
| Self::RecordStop { dataflow } => Some(*dataflow),
Self::Check { dataflow }
| Self::Clean { dataflow, .. }
| Self::LogSubscribe { dataflow, .. }
| Self::GetTraces { dataflow, .. } => *dataflow,
Self::GetParams { scope, .. }
| Self::GetParam { scope, .. }
| Self::SetParam { scope, .. }
| Self::DeleteParam { scope, .. } => scope.dataflow(),
Self::Hello(_)
| Self::Build { .. }
| Self::WaitForBuild { .. }
| Self::Start { .. }
| Self::StopByName { .. }
| Self::RestartByName { .. }
| Self::List { .. }
| Self::Destroy { .. }
| Self::ConnectedDaemons { .. }
| Self::TopicUnsubscribe { .. } => None,
}
}
#[must_use]
pub const fn subscription(&self) -> Option<SubscriptionId> {
match self {
Self::LogSubscribe { subscription, .. }
| Self::TopicSubscribe { subscription, .. }
| Self::TopicUnsubscribe { subscription } => Some(*subscription),
_ => None,
}
}
#[must_use]
pub const fn opens_subscription(&self) -> bool {
matches!(
self,
Self::LogSubscribe { .. } | Self::TopicSubscribe { .. }
)
}
#[must_use]
pub const fn is_blocking(&self) -> bool {
matches!(self, Self::WaitForBuild { .. } | Self::WaitForSpawn { .. })
}
#[must_use]
pub const fn timeout(&self) -> Option<DurationMs> {
match self {
Self::WaitForBuild { timeout, .. } | Self::WaitForSpawn { timeout, .. } => *timeout,
_ => None,
}
}
#[must_use]
pub fn payload_len(&self) -> usize {
match self {
Self::TopicPublish { payload, .. } => payload.len(),
_ => 0,
}
}
#[must_use]
pub fn bitwise_eq(&self, other: &Self) -> bool {
match (self, other) {
(
Self::TopicPublish {
dataflow: left_dataflow,
port: left_port,
metadata: left_metadata,
payload: left_payload,
},
Self::TopicPublish {
dataflow: right_dataflow,
port: right_port,
metadata: right_metadata,
payload: right_payload,
},
) => {
left_dataflow == right_dataflow
&& left_port == right_port
&& left_metadata.bitwise_eq(right_metadata)
&& left_payload == right_payload
}
(
Self::SetParam {
scope: left_scope,
key: left_key,
value: left_value,
create_only: left_create,
},
Self::SetParam {
scope: right_scope,
key: right_key,
value: right_value,
create_only: right_create,
},
) => {
left_scope == right_scope
&& left_key == right_key
&& left_value.bitwise_eq(right_value)
&& left_create == right_create
}
_ => self == other,
}
}
}
impl fmt::Display for ControlRequest {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Hello(hello) => write!(f, "{hello}"),
Self::Build { name, force, .. } => {
let name = name.as_deref().unwrap_or("<unnamed>");
write!(f, "build {name}{}", if *force { " (forced)" } else { "" })
}
Self::WaitForBuild { build, .. } => write!(f, "wait for build {build}"),
Self::Start { source, name, .. } => {
let name = name.as_deref().unwrap_or("<unnamed>");
write!(f, "start {name} from {source}")
}
Self::WaitForSpawn { dataflow, .. } => write!(f, "wait for spawn of {dataflow}"),
Self::Check { dataflow } => match dataflow {
Some(dataflow) => write!(f, "check {dataflow}"),
None => f.write_str("check cluster"),
},
Self::Stop { dataflow, .. } => write!(f, "stop {dataflow}"),
Self::StopByName { name, .. } => write!(f, "stop {name}"),
Self::Restart { dataflow, .. } => write!(f, "restart {dataflow}"),
Self::RestartByName { name, .. } => write!(f, "restart {name}"),
Self::Logs { dataflow, node, .. } => match node {
Some(node) => write!(f, "logs of {dataflow}/{node}"),
None => write!(f, "logs of {dataflow}"),
},
Self::LogSubscribe { subscription, .. } => {
write!(f, "follow logs as subscription {subscription}")
}
Self::List { all } => {
write!(f, "list {} dataflows", if *all { "all" } else { "active" })
}
Self::Info { dataflow, .. } => write!(f, "info for {dataflow}"),
Self::Destroy { force } => {
write!(
f,
"destroy cluster{}",
if *force { " (forced)" } else { "" }
)
}
Self::Clean { dataflow, .. } => match dataflow {
Some(dataflow) => write!(f, "clean {dataflow}"),
None => f.write_str("clean finished dataflows"),
},
Self::ConnectedDaemons { .. } => f.write_str("list daemons"),
Self::GetNodeInfo { dataflow, node } => write!(f, "info for {dataflow}/{node}"),
Self::TopicSubscribe {
port, subscription, ..
} => write!(f, "tap {port} as subscription {subscription}"),
Self::TopicUnsubscribe { subscription } => {
write!(f, "end subscription {subscription}")
}
Self::TopicPublish { port, payload, .. } => {
write!(f, "publish {} bytes to {port}", payload.len())
}
Self::GetParams { scope, .. } => write!(f, "list parameters of {scope}"),
Self::GetParam { scope, key, .. } => write!(f, "get {key} of {scope}"),
Self::SetParam { scope, key, .. } => write!(f, "set {key} of {scope}"),
Self::DeleteParam { scope, key } => write!(f, "delete {key} of {scope}"),
Self::RestartNode { dataflow, node } => write!(f, "restart {dataflow}/{node}"),
Self::StopNode { dataflow, node, .. } => write!(f, "stop {dataflow}/{node}"),
Self::AddNode { dataflow, node, .. } => {
write!(f, "add {} to {dataflow}", node.node)
}
Self::RemoveNode { dataflow, node, .. } => write!(f, "remove {node} from {dataflow}"),
Self::ReplaceNode { dataflow, node, .. } => {
write!(f, "replace {} in {dataflow}", node.node)
}
Self::AddEdge {
dataflow,
consumer,
input,
} => write!(
f,
"connect {} to {dataflow}/{consumer}/{}",
input.source, input.id
),
Self::RemoveEdge {
dataflow,
consumer,
input,
} => write!(f, "disconnect {dataflow}/{consumer}/{input}"),
Self::RecordStart { dataflow, path, .. } => write!(f, "record {dataflow} to {path}"),
Self::RecordStop { dataflow } => write!(f, "stop recording {dataflow}"),
Self::GetTraces { dataflow, .. } => match dataflow {
Some(dataflow) => write!(f, "traces of {dataflow}"),
None => f.write_str("traces of every dataflow"),
},
Self::GetNodeMetrics { dataflow, node } => match node {
Some(node) => write!(f, "metrics for {dataflow}/{node}"),
None => write!(f, "metrics for {dataflow}"),
},
Self::GetManifest { dataflow } => write!(f, "manifest of {dataflow}"),
Self::GetNodeIoMetrics { dataflow, node } => match node {
Some(node) => write!(f, "bandwidth for {dataflow}/{node}"),
None => write!(f, "bandwidth for {dataflow}"),
},
}
}
}
impl_wire_message!(
ControlRequest,
FrameKind::Control,
[
"Hello",
"Build",
"WaitForBuild",
"Start",
"WaitForSpawn",
"Check",
"Stop",
"StopByName",
"Restart",
"RestartByName",
"Logs",
"LogSubscribe",
"List",
"Info",
"Destroy",
"Clean",
"ConnectedDaemons",
"GetNodeInfo",
"TopicSubscribe",
"TopicUnsubscribe",
"TopicPublish",
"GetParams",
"GetParam",
"SetParam",
"DeleteParam",
"RestartNode",
"StopNode",
"AddNode",
"RemoveNode",
"ReplaceNode",
"AddEdge",
"RemoveEdge",
"RecordStart",
"RecordStop",
"GetTraces",
"GetNodeMetrics",
"GetManifest",
"GetNodeIoMetrics",
],
fn variant_index(&self) -> u16 {
match self {
Self::Hello(_) => 0,
Self::Build { .. } => 1,
Self::WaitForBuild { .. } => 2,
Self::Start { .. } => 3,
Self::WaitForSpawn { .. } => 4,
Self::Check { .. } => 5,
Self::Stop { .. } => 6,
Self::StopByName { .. } => 7,
Self::Restart { .. } => 8,
Self::RestartByName { .. } => 9,
Self::Logs { .. } => 10,
Self::LogSubscribe { .. } => 11,
Self::List { .. } => 12,
Self::Info { .. } => 13,
Self::Destroy { .. } => 14,
Self::Clean { .. } => 15,
Self::ConnectedDaemons { .. } => 16,
Self::GetNodeInfo { .. } => 17,
Self::TopicSubscribe { .. } => 18,
Self::TopicUnsubscribe { .. } => 19,
Self::TopicPublish { .. } => 20,
Self::GetParams { .. } => 21,
Self::GetParam { .. } => 22,
Self::SetParam { .. } => 23,
Self::DeleteParam { .. } => 24,
Self::RestartNode { .. } => 25,
Self::StopNode { .. } => 26,
Self::AddNode { .. } => 27,
Self::RemoveNode { .. } => 28,
Self::ReplaceNode { .. } => 29,
Self::AddEdge { .. } => 30,
Self::RemoveEdge { .. } => 31,
Self::RecordStart { .. } => 32,
Self::RecordStop { .. } => 33,
Self::GetTraces { .. } => 34,
Self::GetNodeMetrics { .. } => 35,
Self::GetManifest { .. } => 36,
Self::GetNodeIoMetrics { .. } => 37,
}
}
);
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
use crate::auth::AuthToken;
use crate::codec::{WireDecode, WireEncode, round_trip};
use crate::common::node::NodeSource;
use crate::frame::{FrameFlags, FrameLimits};
use crate::handshake::role::Role;
use crate::messages::WireMessage;
use crate::messages::samples::control_requests;
#[test]
fn the_family_has_the_thirty_five_frozen_verbs_and_its_tail_appends() {
assert_eq!(ControlRequest::VARIANT_NAMES.len(), 38);
assert_eq!(ControlRequest::VARIANT_NAMES[0], "Hello");
assert_eq!(ControlRequest::VARIANT_NAMES[34], "GetTraces");
assert_eq!(ControlRequest::VARIANT_NAMES[35], "GetNodeMetrics");
assert_eq!(ControlRequest::VARIANT_NAMES[36], "GetManifest");
assert_eq!(ControlRequest::VARIANT_NAMES[37], "GetNodeIoMetrics");
}
#[test]
fn every_variant_reports_and_encodes_its_frozen_index() {
let samples = control_requests().unwrap();
assert_eq!(
samples.len(),
ControlRequest::VARIANT_NAMES.len(),
"the sample table must cover every verb"
);
for (index, sample) in samples.iter().enumerate() {
let index = u16::try_from(index).unwrap();
assert_eq!(sample.variant_index(), index, "{sample:?}");
let bytes = sample.encode_to_vec().unwrap();
assert_eq!(u16::from(bytes[0]), index, "{sample:?}");
assert_eq!(
sample.variant_name(),
ControlRequest::VARIANT_NAMES[usize::from(index)]
);
}
}
#[test]
fn every_variant_round_trips_through_a_frame() {
let limits = FrameLimits::uds();
for sample in control_requests().unwrap() {
let bytes = sample.to_frame(FrameFlags::CRC, &limits).unwrap();
let decoded = ControlRequest::from_bytes(&bytes, &limits).unwrap();
assert!(decoded.bitwise_eq(&sample), "{sample:?}");
}
}
#[test]
fn trailing_bytes_after_a_request_are_refused() {
for sample in control_requests().unwrap() {
let mut bytes = sample.encode_to_vec().unwrap();
bytes.push(0xFF);
assert!(matches!(
ControlRequest::decode_exact(&bytes),
Err(crate::error::WireError::TrailingBytes { .. })
));
}
}
#[test]
fn every_verb_is_classified_and_the_split_matches_the_blueprint() {
for sample in control_requests().unwrap() {
let scope = sample.scope();
assert_eq!(scope.is_mutating(), sample.is_mutating());
assert_ne!(sample.is_mutating(), sample.is_read_only());
}
assert!(ControlRequest::List { all: false }.is_read_only());
assert!(
ControlRequest::Logs {
dataflow: DataflowId::from_u128(1),
node: None,
query: LogQuery::new(),
}
.is_read_only()
);
assert!(
ControlRequest::TopicSubscribe {
dataflow: DataflowId::from_u128(1),
port: "camera/image".parse().unwrap(),
query: TopicQuery::new(),
subscription: SubscriptionId::FIRST,
}
.is_read_only()
);
assert!(
ControlRequest::Start {
source: DataflowSource::from_manifest("nodes: []"),
name: None,
detach: false,
}
.is_mutating()
);
assert!(
ControlRequest::Stop {
dataflow: DataflowId::from_u128(1),
grace: None,
}
.is_mutating()
);
assert!(
ControlRequest::SetParam {
scope: ParamScope::Global,
key: ParamKey::new("gain").unwrap(),
value: Parameter::Integer(1),
create_only: false,
}
.is_mutating()
);
}
#[test]
fn the_read_and_mutate_sets_partition_the_family() {
let mut read = 0usize;
let mut mutate = 0usize;
for sample in control_requests().unwrap() {
if sample.is_mutating() {
mutate += 1;
} else {
read += 1;
}
}
assert_eq!(read + mutate, ControlRequest::VARIANT_NAMES.len());
assert!(read > 0 && mutate > 0);
}
#[test]
fn get_manifest_is_read_only_and_addresses_its_dataflow() {
let request = ControlRequest::GetManifest {
dataflow: DataflowId::from_u128(1),
};
assert!(request.is_read_only());
assert_eq!(request.dataflow(), Some(DataflowId::from_u128(1)));
assert!(request.to_string().contains("manifest"));
}
#[test]
fn get_node_metrics_is_a_read_only_poll_not_a_subscription() {
let request = ControlRequest::GetNodeMetrics {
dataflow: DataflowId::from_u128(1),
node: None,
};
assert!(request.is_read_only());
assert_eq!(request.dataflow(), Some(DataflowId::from_u128(1)));
assert_eq!(request.subscription(), None);
assert!(!request.opens_subscription());
assert!(request.to_string().contains("metrics"));
}
#[test]
fn a_publish_is_mutating_even_though_it_reads_like_a_topic_verb() {
let publish = ControlRequest::TopicPublish {
dataflow: DataflowId::from_u128(1),
port: "camera/image".parse().unwrap(),
metadata: Metadata::new(HlcTimestamp::new(1, 0)),
payload: vec![1, 2, 3],
};
assert!(publish.is_mutating());
assert_eq!(publish.payload_len(), 3);
}
#[test]
fn the_handshake_is_recognised_and_grants_nothing() {
let hello = Hello::new(Role::Cli, AuthToken::ZERO);
let request = ControlRequest::Hello(hello.clone());
assert!(request.is_handshake());
assert_eq!(request.hello(), Some(&hello));
assert!(request.is_read_only());
assert!(!ControlRequest::List { all: true }.is_handshake());
assert_eq!(ControlRequest::List { all: true }.hello(), None);
}
#[test]
fn dataflow_addressing_is_reported_where_it_exists() {
let id = DataflowId::from_u128(0x1234);
assert_eq!(
ControlRequest::Stop {
dataflow: id,
grace: None
}
.dataflow(),
Some(id)
);
assert_eq!(
ControlRequest::Check { dataflow: Some(id) }.dataflow(),
Some(id)
);
assert_eq!(ControlRequest::Check { dataflow: None }.dataflow(), None);
assert_eq!(
ControlRequest::GetParam {
scope: ParamScope::dataflow_scope(id),
key: ParamKey::new("gain").unwrap(),
inherited: true,
}
.dataflow(),
Some(id)
);
assert_eq!(
ControlRequest::StopByName {
name: "demo".to_owned(),
grace: None
}
.dataflow(),
None,
"resolving a name needs the coordinator's registry"
);
assert_eq!(ControlRequest::Destroy { force: true }.dataflow(), None);
}
#[test]
fn subscription_accessors_cover_the_three_subscription_verbs() {
let subscription = SubscriptionId::new(11);
let subscribe = ControlRequest::TopicSubscribe {
dataflow: DataflowId::from_u128(1),
port: "camera/image".parse().unwrap(),
query: TopicQuery::new(),
subscription,
};
assert_eq!(subscribe.subscription(), Some(subscription));
assert!(subscribe.opens_subscription());
let unsubscribe = ControlRequest::TopicUnsubscribe { subscription };
assert_eq!(unsubscribe.subscription(), Some(subscription));
assert!(!unsubscribe.opens_subscription());
assert_eq!(ControlRequest::List { all: false }.subscription(), None);
}
#[test]
fn blocking_verbs_expose_their_deadlines() {
let build = ControlRequest::WaitForBuild {
build: BuildId::from_u128(1),
timeout: Some(DurationMs::from_secs(30)),
};
assert!(build.is_blocking());
assert_eq!(build.timeout(), Some(DurationMs::from_secs(30)));
let list = ControlRequest::List { all: false };
assert!(!list.is_blocking());
assert_eq!(list.timeout(), None);
}
#[test]
fn a_spawn_spec_survives_the_wire_intact() {
let spec = NodeSpawnSpec::new(
DataflowId::from_u128(1),
NodeId::new("camera").unwrap(),
3,
NodeSource::Executable {
path: "./target/release/camera".to_owned(),
},
);
let request = ControlRequest::AddNode {
dataflow: DataflowId::from_u128(1),
node: Box::new(spec.clone()),
start: true,
};
let decoded = round_trip(&request).unwrap();
match decoded {
ControlRequest::AddNode { node, start, .. } => {
assert_eq!(*node, spec);
assert!(start);
}
other => panic!("expected AddNode, got {other:?}"),
}
}
#[test]
fn nan_parameters_survive_the_wire() {
let request = ControlRequest::SetParam {
scope: ParamScope::Global,
key: ParamKey::new("gain").unwrap(),
value: Parameter::Float(f64::NAN),
create_only: false,
};
let decoded = round_trip(&request).unwrap();
assert_ne!(decoded, request);
assert!(decoded.bitwise_eq(&request));
}
#[test]
fn display_names_every_verb_without_panicking() {
for sample in control_requests().unwrap() {
assert!(
!sample.to_string().is_empty(),
"{} rendered empty",
sample.variant_name()
);
}
}
#[test]
fn serde_round_trips_the_family_for_diagnostics() {
for sample in control_requests().unwrap() {
let json = serde_json::to_string(&sample).unwrap();
let back: ControlRequest = serde_json::from_str(&json).unwrap();
assert!(back.bitwise_eq(&sample));
}
}
}