1use bytemuck::NoUninit;
2use chrono::{DateTime, SecondsFormat, Utc};
3use serde::{Deserialize, Serialize};
4use serde_json::Value as JsonValue;
5use std::collections::BTreeMap;
6use utoipa::ToSchema;
7use uuid::Uuid;
8
9use crate::{
10 checkpoint::CheckpointActivity,
11 coordination::Step,
12 memory_pressure::MemoryPressure,
13 suspend::{PermanentSuspendError, SuspendError},
14 transaction::{CommitProgressSummary, ConcurrentBootstrapPhase, TransactionId},
15};
16
17#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
19#[serde(rename_all = "PascalCase")]
20pub enum PipelineState {
21 #[default]
23 Paused,
24 Running,
26 Terminated,
28}
29
30#[derive(Default, Serialize, Deserialize, Debug, Clone)]
34pub struct InputEndpointErrorMetrics {
35 pub endpoint_name: String,
36 #[serde(default)]
37 pub num_transport_errors: u64,
38 #[serde(default)]
39 pub num_parse_errors: u64,
40}
41
42#[derive(Default, Serialize, Deserialize, Debug, Clone)]
46pub struct OutputEndpointErrorMetrics {
47 pub endpoint_name: String,
48 #[serde(default)]
49 pub num_encode_errors: u64,
50 #[serde(default)]
51 pub num_transport_errors: u64,
52}
53
54#[derive(Serialize, Deserialize, Debug, Clone)]
58pub struct EndpointErrorStats<T> {
59 #[serde(default)]
60 pub metrics: T,
61}
62
63#[derive(Debug, Deserialize, Serialize, ToSchema)]
65pub struct ShortEndpointConfig {
66 pub stream: String,
68}
69
70#[derive(Serialize, Deserialize, Debug, Clone)]
74pub struct PipelineStatsErrorsResponse {
75 #[serde(default)]
76 pub inputs: Vec<EndpointErrorStats<InputEndpointErrorMetrics>>,
77 #[serde(default)]
78 pub outputs: Vec<EndpointErrorStats<OutputEndpointErrorMetrics>>,
79}
80
81#[derive(
86 Debug, Default, Copy, PartialEq, Eq, Clone, NoUninit, Serialize, Deserialize, ToSchema,
87)]
88#[repr(u8)]
89pub enum TransactionStatus {
90 #[default]
91 NoTransaction,
92 TransactionInProgress,
93 CommitInProgress,
94}
95
96#[derive(Clone, Copy, PartialEq, Eq, Debug, Deserialize, Serialize, ToSchema)]
98#[serde(rename_all = "PascalCase")]
99#[schema(as = TransactionPhase)]
100pub enum ExternalTransactionPhase {
101 Started,
103 Committed,
105}
106
107#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize, ToSchema)]
109#[schema(as = ConnectorTransactionPhase)]
110pub struct ExternalConnectorTransactionPhase {
111 #[schema(value_type = TransactionPhase)]
113 pub phase: ExternalTransactionPhase,
114 pub label: Option<String>,
116}
117
118#[derive(Clone, Default, Debug, Deserialize, Serialize, ToSchema)]
120#[schema(as = TransactionInitiators)]
121pub struct ExternalTransactionInitiators {
122 #[schema(value_type = Option<i64>)]
124 pub transaction_id: Option<TransactionId>,
125 #[schema(value_type = Option<TransactionPhase>)]
127 pub initiated_by_api: Option<ExternalTransactionPhase>,
128 #[schema(value_type = BTreeMap<String, ConnectorTransactionPhase>)]
130 pub initiated_by_connectors: BTreeMap<String, ExternalConnectorTransactionPhase>,
131}
132
133#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]
135pub struct CompletedWatermark {
136 #[schema(value_type = Object)]
138 pub metadata: JsonValue,
139 #[serde(serialize_with = "serialize_timestamp_micros")]
141 pub ingested_at: DateTime<Utc>,
142 #[serde(serialize_with = "serialize_timestamp_micros")]
144 pub processed_at: DateTime<Utc>,
145 #[serde(serialize_with = "serialize_timestamp_micros")]
147 pub completed_at: DateTime<Utc>,
148}
149
150#[derive(Debug, Default, Deserialize, Serialize, ToSchema, Clone)]
151pub enum ConnectorHealthStatus {
152 #[default]
153 Healthy,
154 Unhealthy,
155}
156
157#[derive(Debug, Default, Deserialize, Serialize, ToSchema, Clone)]
158pub struct ConnectorHealth {
159 pub status: ConnectorHealthStatus,
160 pub description: Option<String>,
161}
162
163impl ConnectorHealth {
164 pub fn healthy() -> Self {
165 Self {
166 status: ConnectorHealthStatus::Healthy,
167 description: None,
168 }
169 }
170 pub fn unhealthy(description: &str) -> Self {
171 Self {
172 status: ConnectorHealthStatus::Unhealthy,
173 description: Some(description.to_string()),
174 }
175 }
176}
177
178#[derive(Debug, Default, Deserialize, Serialize, ToSchema, Clone, PartialEq, Eq)]
179pub struct ConnectorError {
180 #[serde(serialize_with = "serialize_timestamp_micros")]
182 pub timestamp: DateTime<Utc>,
183
184 pub index: u64,
190
191 pub tag: Option<String>,
195
196 pub message: String,
198}
199
200#[derive(Debug, Default, Deserialize, Serialize, ToSchema)]
202#[schema(as = InputEndpointMetrics)]
203pub struct ExternalInputEndpointMetrics {
204 pub total_bytes: u64,
206 pub total_records: u64,
208 pub buffered_records: u64,
210 pub buffered_bytes: u64,
212 pub num_transport_errors: u64,
214 pub num_parse_errors: u64,
216 pub end_of_input: bool,
218 #[serde(default, skip_serializing_if = "Option::is_none")]
234 pub processing_latency_p99_micros: Option<u64>,
235}
236
237impl ExternalInputEndpointMetrics {
238 pub fn merge(&mut self, other: &Self) {
241 let &Self {
244 total_bytes,
245 total_records,
246 buffered_records,
247 buffered_bytes,
248 num_transport_errors,
249 num_parse_errors,
250 end_of_input,
251 processing_latency_p99_micros,
252 } = other;
253 self.total_bytes += total_bytes;
254 self.total_records += total_records;
255 self.buffered_records += buffered_records;
256 self.buffered_bytes += buffered_bytes;
257 self.num_transport_errors += num_transport_errors;
258 self.num_parse_errors += num_parse_errors;
259 self.end_of_input &= end_of_input;
260 self.processing_latency_p99_micros = self
262 .processing_latency_p99_micros
263 .max(processing_latency_p99_micros);
264 }
265}
266
267#[derive(Debug, Serialize, Deserialize, ToSchema)]
269#[schema(as = InputEndpointStatus)]
270pub struct ExternalInputEndpointStatus {
271 pub endpoint_name: String,
273 pub config: ShortEndpointConfig,
275 #[schema(value_type = InputEndpointMetrics)]
277 pub metrics: ExternalInputEndpointMetrics,
278 pub fatal_error: Option<String>,
280 #[serde(default, skip_serializing_if = "Option::is_none")]
282 pub parse_errors: Option<Vec<ConnectorError>>,
283 #[serde(default, skip_serializing_if = "Option::is_none")]
285 pub transport_errors: Option<Vec<ConnectorError>>,
286 #[serde(default)]
288 pub health: Option<ConnectorHealth>,
289 pub paused: bool,
292 pub barrier: bool,
294 #[schema(value_type = Option<CompletedWatermark>)]
296 pub completed_frontier: Option<CompletedWatermark>,
297}
298
299#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
303pub enum FrontierMerge {
304 Shared,
308
309 Partitioned,
313
314 #[default]
318 Opaque,
319}
320
321impl ExternalInputEndpointStatus {
322 pub fn merge(&mut self, other: Self, frontier_merge: FrontierMerge) {
338 let Self {
341 endpoint_name: _,
343 config: _,
344 metrics,
345 fatal_error,
346 parse_errors,
347 transport_errors,
348 health,
349 paused,
350 barrier,
351 completed_frontier,
352 } = other;
353 let (a_eoi, b_eoi) = (self.metrics.end_of_input, metrics.end_of_input);
354 self.metrics.merge(&metrics);
355 if self.fatal_error.is_none() {
356 self.fatal_error = fatal_error;
357 }
358 merge_errors(&mut self.parse_errors, parse_errors);
359 merge_errors(&mut self.transport_errors, transport_errors);
360 self.health = match (self.health.take(), health) {
361 (Some(a), Some(b)) => Some(if matches!(a.status, ConnectorHealthStatus::Unhealthy) {
362 a
363 } else {
364 b
365 }),
366 (a, b) => a.or(b),
367 };
368 self.paused &= paused;
369 self.barrier |= barrier;
370 let (a, b) = (self.completed_frontier.take(), completed_frontier);
371 let several = !a_eoi && !b_eoi && a.is_some() && b.is_some();
372 let no_partitions = serde_json::json!({"partitions": [], "offsets": []});
375 let metadata = |f: &Option<CompletedWatermark>| {
376 f.as_ref().map_or(&no_partitions, |f| &f.metadata).clone()
377 };
378 let joined = join_partitions(&metadata(&a), &metadata(&b));
379 let oldest = |a: CompletedWatermark, b: CompletedWatermark| {
380 if b.ingested_at < a.ingested_at { b } else { a }
381 };
382 let newest = |a: CompletedWatermark, b: CompletedWatermark| {
383 if b.ingested_at > a.ingested_at { b } else { a }
384 };
385 self.completed_frontier = match (a_eoi, b_eoi) {
386 (false, false) => a.zip(b).map(|(a, b)| oldest(a, b)),
387 (false, true) => a,
388 (true, false) => b,
389 (true, true) => match (a, b) {
390 (Some(a), Some(b)) => Some(newest(a, b)),
391 (a, b) => a.or(b),
392 },
393 };
394 if let Some(frontier) = &mut self.completed_frontier {
395 match frontier_merge {
396 FrontierMerge::Shared => (),
397 FrontierMerge::Partitioned => frontier.metadata = joined,
398 FrontierMerge::Opaque => {
399 if several {
400 frontier.metadata = JsonValue::Null;
401 }
402 }
403 }
404 }
405 }
406}
407
408fn join_partitions(a: &JsonValue, b: &JsonValue) -> JsonValue {
412 fn pairs(metadata: &JsonValue) -> Option<Vec<(i64, &JsonValue)>> {
413 let partitions = metadata.get("partitions")?.as_array()?;
414 let offsets = metadata.get("offsets")?.as_array()?;
415 if partitions.len() != offsets.len() {
416 return None;
417 }
418 partitions
419 .iter()
420 .zip(offsets)
421 .map(|(partition, offsets)| Some((partition.as_i64()?, offsets)))
422 .collect()
423 }
424 let (Some(a), Some(b)) = (pairs(a), pairs(b)) else {
425 return JsonValue::Null;
426 };
427 let mut joined = BTreeMap::new();
428 for (partition, offsets) in a.into_iter().chain(b) {
429 if joined.insert(partition, offsets.clone()).is_some() {
430 return JsonValue::Null;
431 }
432 }
433 let (partitions, offsets): (Vec<_>, Vec<_>) = joined.into_iter().unzip();
434 serde_json::json!({"partitions": partitions, "offsets": offsets})
435}
436
437fn merge_errors(a: &mut Option<Vec<ConnectorError>>, b: Option<Vec<ConnectorError>>) {
440 if let Some(b) = b {
441 let errors = a.get_or_insert_with(Vec::new);
442 errors.extend(b);
443 errors.sort_by_key(|error| error.timestamp);
444 }
445}
446
447#[derive(Debug, Default, Deserialize, Serialize, ToSchema, PartialEq, Eq, PartialOrd, Ord)]
449#[schema(as = OutputEndpointMetrics)]
450pub struct ExternalOutputEndpointMetrics {
451 pub transmitted_records: u64,
453 pub transmitted_bytes: u64,
455 pub queued_records: u64,
457 pub queued_batches: u64,
459 pub buffered_records: u64,
461 pub buffered_batches: u64,
463 pub num_encode_errors: u64,
465 pub num_transport_errors: u64,
467 pub total_processed_input_records: u64,
486 #[schema(value_type = u64)]
500 pub total_processed_steps: Step,
501 pub memory: u64,
503 #[serde(default, skip_serializing_if = "Option::is_none")]
508 pub batch_records_written: Option<u64>,
509}
510
511#[derive(Debug, Deserialize, Serialize, ToSchema)]
513#[schema(as = OutputEndpointStatus)]
514pub struct ExternalOutputEndpointStatus {
515 pub endpoint_name: String,
517 pub config: ShortEndpointConfig,
519 #[schema(value_type = OutputEndpointMetrics)]
521 pub metrics: ExternalOutputEndpointMetrics,
522 pub fatal_error: Option<String>,
524 #[serde(default, skip_serializing_if = "Option::is_none")]
526 pub encode_errors: Option<Vec<ConnectorError>>,
527 #[serde(default, skip_serializing_if = "Option::is_none")]
529 pub transport_errors: Option<Vec<ConnectorError>>,
530 #[serde(default)]
532 pub health: Option<ConnectorHealth>,
533 #[serde(default)]
538 pub paused: bool,
539}
540
541#[derive(Debug, Default, Serialize, Deserialize, ToSchema)]
543#[schema(as = GlobalControllerMetrics)]
544pub struct ExternalGlobalControllerMetrics {
545 pub state: PipelineState,
547 pub bootstrap_in_progress: bool,
549 pub transaction_status: TransactionStatus,
551 #[schema(value_type = i64)]
553 pub transaction_id: TransactionId,
554 pub transaction_msecs: Option<u64>,
562 pub transaction_records: Option<u64>,
570 pub commit_progress: Option<CommitProgressSummary>,
572 #[schema(value_type = TransactionInitiators)]
574 pub transaction_initiators: ExternalTransactionInitiators,
575 pub concurrent_bootstrap_phase: ConcurrentBootstrapPhase,
577 pub concurrent_bootstrap_progress: Option<CommitProgressSummary>,
581 pub rss_bytes: u64,
583 pub memory_pressure: MemoryPressure,
585 pub memory_pressure_epoch: u64,
587 pub cpu_msecs: u64,
589 pub uptime_msecs: u64,
594 #[serde(with = "chrono::serde::ts_seconds")]
596 #[schema(value_type = u64)]
597 pub start_time: DateTime<Utc>,
598 pub incarnation_uuid: Uuid,
600 #[serde(with = "chrono::serde::ts_seconds")]
602 #[schema(value_type = u64)]
603 pub initial_start_time: DateTime<Utc>,
604 pub storage_bytes: u64,
606 pub storage_mb_secs: u64,
608 #[serde(default, skip_serializing_if = "Option::is_none")]
610 pub disk_total_bytes: Option<u64>,
611 #[serde(default, skip_serializing_if = "Option::is_none")]
613 pub disk_available_bytes: Option<u64>,
614 pub runtime_elapsed_msecs: u64,
616 pub buffered_input_records: u64,
618 pub buffered_input_bytes: u64,
620 pub total_input_records: u64,
622 pub total_input_bytes: u64,
624 pub total_processed_records: u64,
626 pub total_processed_bytes: u64,
628 pub total_completed_records: u64,
636 pub output_stall_msecs: u64,
646 #[schema(value_type = u64)]
655 pub total_initiated_steps: Step,
656 #[schema(value_type = u64)]
670 pub total_completed_steps: Step,
671 pub pipeline_complete: bool,
673 pub platform_version: String,
679 pub runtime_version: String,
685}
686
687#[derive(Debug, Deserialize, Serialize, ToSchema, Default)]
695#[schema(as = ControllerStatus)]
696pub struct ExternalControllerStatus {
697 #[schema(value_type = GlobalControllerMetrics)]
699 pub global_metrics: ExternalGlobalControllerMetrics,
700 pub suspend_error: Option<SuspendError>,
702 pub checkpoint_activity: Option<CheckpointActivity>,
705 pub permanent_checkpoint_errors: Option<Vec<PermanentSuspendError>>,
710 #[schema(value_type = Vec<InputEndpointStatus>)]
712 pub inputs: Vec<ExternalInputEndpointStatus>,
713 #[schema(value_type = Vec<OutputEndpointStatus>)]
715 pub outputs: Vec<ExternalOutputEndpointStatus>,
716 #[serde(default, skip_serializing_if = "Vec::is_empty")]
718 pub host_metrics: Vec<HostMetrics>,
719}
720
721#[derive(Debug, Default, Deserialize, Serialize, ToSchema)]
723pub struct HostMetrics {
724 #[serde(default, skip_serializing_if = "Option::is_none")]
726 pub disk_total_bytes: Option<u64>,
727 #[serde(default, skip_serializing_if = "Option::is_none")]
729 pub disk_available_bytes: Option<u64>,
730}
731
732impl From<&ExternalGlobalControllerMetrics> for HostMetrics {
733 fn from(metrics: &ExternalGlobalControllerMetrics) -> Self {
734 Self {
735 disk_total_bytes: metrics.disk_total_bytes,
736 disk_available_bytes: metrics.disk_available_bytes,
737 }
738 }
739}
740
741fn serialize_timestamp_micros<S>(
742 timestamp: &DateTime<Utc>,
743 serializer: S,
744) -> Result<S::Ok, S::Error>
745where
746 S: serde::Serializer,
747{
748 serializer.serialize_str(×tamp.to_rfc3339_opts(SecondsFormat::Micros, true))
749}
750
751#[cfg(test)]
752mod tests {
753 use super::ConnectorError;
754 use chrono::{DateTime, Utc};
755
756 #[test]
757 fn connector_error_timestamp_serializes_with_microsecond_precision() {
758 let error = ConnectorError {
759 timestamp: DateTime::parse_from_rfc3339("2026-03-08T05:26:42.442438448Z")
760 .unwrap()
761 .with_timezone(&Utc),
762 index: 1,
763 tag: None,
764 message: "boom".to_string(),
765 };
766
767 let json = serde_json::to_string(&error).unwrap();
768 assert!(json.contains(r#""timestamp":"2026-03-08T05:26:42.442438Z""#));
769 }
770
771 #[test]
772 fn output_metrics_batch_records_written_serializes() {
773 use super::ExternalOutputEndpointMetrics;
774
775 let metrics = ExternalOutputEndpointMetrics {
776 batch_records_written: Some(42),
777 ..Default::default()
778 };
779 let json = serde_json::to_string(&metrics).unwrap();
780 assert!(json.contains(r#""batch_records_written":42"#));
781
782 let deserialized: ExternalOutputEndpointMetrics = serde_json::from_str(&json).unwrap();
783 assert_eq!(deserialized.batch_records_written, Some(42));
784 }
785
786 #[test]
787 fn output_metrics_batch_records_written_defaults_to_none() {
788 use super::ExternalOutputEndpointMetrics;
789
790 let json = r#"{"transmitted_records":0,"transmitted_bytes":0,"queued_records":0,"queued_batches":0,"buffered_records":0,"buffered_batches":0,"num_encode_errors":0,"num_transport_errors":0,"total_processed_input_records":0,"total_processed_steps":0,"memory":0}"#;
792 let metrics: ExternalOutputEndpointMetrics = serde_json::from_str(json).unwrap();
793 assert_eq!(metrics.batch_records_written, None);
794 }
795
796 mod merge {
797 use chrono::{DateTime, TimeZone, Utc};
798
799 use crate::adapter_stats::{
800 CompletedWatermark, ConnectorError, ConnectorHealth, ConnectorHealthStatus,
801 ExternalInputEndpointMetrics, ExternalInputEndpointStatus, FrontierMerge,
802 ShortEndpointConfig,
803 };
804 use serde_json::{Value, json};
805
806 fn time(secs: i64) -> DateTime<Utc> {
807 Utc.timestamp_opt(secs, 0).unwrap()
808 }
809
810 fn error(secs: i64, message: &str) -> ConnectorError {
811 ConnectorError {
812 timestamp: time(secs),
813 index: 0,
814 tag: None,
815 message: message.into(),
816 }
817 }
818
819 fn frontier(ingested_secs: i64) -> CompletedWatermark {
820 CompletedWatermark {
821 metadata: serde_json::json!(ingested_secs),
822 ingested_at: time(ingested_secs),
823 processed_at: time(ingested_secs + 1),
824 completed_at: time(ingested_secs + 2),
825 }
826 }
827
828 fn status() -> ExternalInputEndpointStatus {
829 ExternalInputEndpointStatus {
830 endpoint_name: "t.kafka".into(),
831 config: ShortEndpointConfig { stream: "t".into() },
832 metrics: ExternalInputEndpointMetrics {
833 total_bytes: 10,
834 total_records: 1,
835 buffered_records: 2,
836 buffered_bytes: 20,
837 num_transport_errors: 3,
838 num_parse_errors: 4,
839 end_of_input: true,
840 processing_latency_p99_micros: Some(100),
841 },
842 fatal_error: None,
843 parse_errors: None,
844 transport_errors: None,
845 health: Some(ConnectorHealth::healthy()),
846 paused: false,
847 barrier: false,
848 completed_frontier: None,
849 }
850 }
851
852 #[test]
853 fn counters_add_up() {
854 let mut a = status();
855 let mut b = status();
856 b.metrics.processing_latency_p99_micros = Some(500);
857 b.metrics.end_of_input = false;
858 a.merge(b, FrontierMerge::Opaque);
859 let m = &a.metrics;
860 assert_eq!(
861 (
862 m.total_bytes,
863 m.total_records,
864 m.buffered_records,
865 m.buffered_bytes
866 ),
867 (20, 2, 4, 40)
868 );
869 assert_eq!((m.num_transport_errors, m.num_parse_errors), (6, 8));
870 assert!(!m.end_of_input);
871 assert_eq!(m.processing_latency_p99_micros, Some(500));
872 }
873
874 #[test]
875 fn worst_host_decides() {
876 let mut a = status();
877 let mut b = status();
878 b.fatal_error = Some("broken".into());
879 b.health = Some(ConnectorHealth::unhealthy("sick"));
880 b.barrier = true;
881 a.merge(b, FrontierMerge::Opaque);
882 assert_eq!(a.fatal_error.as_deref(), Some("broken"));
883 assert!(matches!(
884 a.health.unwrap().status,
885 ConnectorHealthStatus::Unhealthy
886 ));
887 assert!(a.barrier);
888
889 let mut a = status();
891 a.fatal_error = Some("first".into());
892 let mut b = status();
893 b.fatal_error = Some("second".into());
894 a.merge(b, FrontierMerge::Opaque);
895 assert_eq!(a.fatal_error.as_deref(), Some("first"));
896 }
897
898 fn merge_metadata(
902 hosts: Vec<(bool, Option<(i64, Value)>)>,
903 kind: FrontierMerge,
904 ) -> Option<(DateTime<Utc>, Value)> {
905 let mut statuses = hosts.into_iter().map(|(eoi, f)| {
906 let mut s = status();
907 s.metrics.end_of_input = eoi;
908 s.completed_frontier = f.map(|(secs, metadata)| CompletedWatermark {
909 metadata,
910 ..frontier(secs)
911 });
912 s
913 });
914 let mut x = statuses.next().unwrap();
915 statuses.for_each(|y| x.merge(y, kind));
916 x.completed_frontier.map(|f| (f.ingested_at, f.metadata))
917 }
918
919 #[test]
922 fn shared_frontier_merge() {
923 let merged = |hosts| merge_metadata(hosts, FrontierMerge::Shared);
924 let version = |v: i64| json!({"version": v});
925 assert_eq!(
926 merged(vec![
927 (false, Some((10, version(3)))),
928 (false, Some((5, version(2))))
929 ]),
930 Some((time(5), version(2)))
931 );
932 assert_eq!(
933 merged(vec![
934 (true, Some((5, version(2)))),
935 (false, Some((10, version(7))))
936 ]),
937 Some((time(10), version(7)))
938 );
939 assert_eq!(
940 merged(vec![
941 (true, Some((5, version(2)))),
942 (true, Some((10, version(2))))
943 ]),
944 Some((time(10), version(2)))
945 );
946 }
947
948 #[test]
951 fn partitioned_frontier_merge() {
952 let merged = |hosts| merge_metadata(hosts, FrontierMerge::Partitioned);
953 let host = |partitions: &[i64], offsets: &[i64]| json!({"partitions": partitions, "offsets": offsets, "shard": {"host": 0}});
955 let joined = |partitions: &[i64], offsets: &[i64]| json!({"partitions": partitions, "offsets": offsets});
956
957 assert_eq!(
959 merged(vec![
960 (false, Some((10, host(&[1, 4], &[11, 14])))),
961 (false, Some((5, host(&[2], &[12])))),
962 (false, Some((7, host(&[0, 3], &[10, 13])))),
963 ]),
964 Some((time(5), joined(&[0, 1, 2, 3, 4], &[10, 11, 12, 13, 14])))
965 );
966
967 assert_eq!(
969 merged(vec![
970 (true, Some((5, host(&[1], &[11])))),
971 (false, Some((10, host(&[0], &[10])))),
972 ]),
973 Some((time(10), joined(&[0, 1], &[10, 11])))
974 );
975 assert_eq!(
976 merged(vec![
977 (true, Some((10, host(&[1], &[11])))),
978 (true, Some((5, host(&[0], &[10])))),
979 ]),
980 Some((time(10), joined(&[0, 1], &[10, 11])))
981 );
982
983 assert_eq!(
986 merged(vec![(true, None), (false, Some((10, host(&[0], &[10]))))]),
987 Some((time(10), joined(&[0], &[10])))
988 );
989
990 assert_eq!(
992 merged(vec![(false, None), (true, Some((10, host(&[0], &[10]))))]),
993 None
994 );
995
996 for other in [json!({"offsets": [11]}), host(&[0], &[11]), Value::Null] {
999 assert_eq!(
1000 merged(vec![
1001 (false, Some((10, host(&[0], &[10])))),
1002 (false, Some((5, other.clone()))),
1003 ]),
1004 Some((time(5), Value::Null)),
1005 "{other}"
1006 );
1007 }
1008 }
1009
1010 #[test]
1012 fn pause_merge() {
1013 let merged = |hosts: &[bool]| {
1014 let mut statuses = hosts.iter().map(|&paused| {
1015 let mut s = status();
1016 s.paused = paused;
1017 s
1018 });
1019 let mut x = statuses.next().unwrap();
1020 statuses.for_each(|y| x.merge(y, FrontierMerge::Opaque));
1021 x.paused
1022 };
1023 assert!(merged(&[true, true, true]));
1024 assert!(!merged(&[false, false, false]));
1025 for hosts in [
1026 [true, false, false],
1027 [false, true, false],
1028 [false, false, true],
1029 [true, true, false],
1030 [false, true, true],
1031 [true, false, true],
1032 ] {
1033 assert!(!merged(&hosts), "{hosts:?}");
1034 }
1035 }
1036
1037 #[test]
1038 fn errors_are_combined_in_time_order() {
1039 let mut a = status();
1040 a.parse_errors = Some(vec![error(1, "a1"), error(5, "a5")]);
1041 let mut b = status();
1042 b.parse_errors = Some(vec![error(3, "b3")]);
1043 b.transport_errors = Some(vec![error(2, "b2")]);
1044 a.merge(b, FrontierMerge::Opaque);
1045 let messages = |errors: &Option<Vec<ConnectorError>>| {
1046 errors
1047 .iter()
1048 .flatten()
1049 .map(|e| e.message.clone())
1050 .collect::<Vec<_>>()
1051 };
1052 assert_eq!(messages(&a.parse_errors), ["a1", "b3", "a5"]);
1053 assert_eq!(messages(&a.transport_errors), ["b2"]);
1054 }
1055
1056 #[test]
1057 fn opaque_frontier_merge() {
1058 let merged = |hosts: &[(bool, Option<i64>)]| {
1061 let mut statuses = hosts.iter().map(|&(eoi, f)| {
1062 let mut s = status();
1063 s.metrics.end_of_input = eoi;
1064 s.completed_frontier = f.map(frontier);
1065 s
1066 });
1067 let mut x = statuses.next().unwrap();
1068 statuses.for_each(|y| x.merge(y, FrontierMerge::Opaque));
1069 x.completed_frontier
1070 .map(|f| (f.ingested_at, !f.metadata.is_null()))
1071 };
1072 let (busy, done) = (false, true);
1073
1074 assert_eq!(
1076 merged(&[(busy, Some(10)), (busy, Some(5))]),
1077 Some((time(5), false))
1078 );
1079 assert_eq!(
1080 merged(&[(busy, Some(5)), (busy, Some(10))]),
1081 Some((time(5), false))
1082 );
1083
1084 assert_eq!(merged(&[(busy, None), (busy, Some(10))]), None);
1087 assert_eq!(merged(&[(busy, Some(10)), (busy, None)]), None);
1088 assert_eq!(
1089 merged(&[(busy, Some(10)), (busy, None), (busy, Some(5))]),
1090 None
1091 );
1092 assert_eq!(
1093 merged(&[(busy, None), (done, Some(5)), (busy, Some(10))]),
1094 None
1095 );
1096
1097 assert_eq!(
1101 merged(&[(busy, Some(10)), (done, Some(5))]),
1102 Some((time(10), true))
1103 );
1104 assert_eq!(
1105 merged(&[(done, Some(5)), (busy, Some(10))]),
1106 Some((time(10), true))
1107 );
1108 assert_eq!(
1109 merged(&[(done, None), (busy, Some(10))]),
1110 Some((time(10), true))
1111 );
1112 assert_eq!(
1113 merged(&[(busy, Some(10)), (done, None)]),
1114 Some((time(10), true))
1115 );
1116 assert_eq!(
1117 merged(&[(done, Some(5)), (busy, Some(10)), (done, Some(20))]),
1118 Some((time(10), true))
1119 );
1120 assert_eq!(
1121 merged(&[(done, Some(5)), (busy, Some(10)), (busy, Some(20))]),
1122 Some((time(10), false))
1123 );
1124
1125 assert_eq!(
1127 merged(&[(done, Some(10)), (done, Some(5))]),
1128 Some((time(10), true))
1129 );
1130 assert_eq!(
1131 merged(&[(done, None), (done, Some(5))]),
1132 Some((time(5), true))
1133 );
1134 assert_eq!(merged(&[(done, None), (done, None)]), None);
1135 }
1136 }
1137}