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,
483 #[schema(value_type = u64)]
497 pub total_processed_steps: Step,
498 pub memory: u64,
500 #[serde(default, skip_serializing_if = "Option::is_none")]
505 pub batch_records_written: Option<u64>,
506}
507
508#[derive(Debug, Deserialize, Serialize, ToSchema)]
510#[schema(as = OutputEndpointStatus)]
511pub struct ExternalOutputEndpointStatus {
512 pub endpoint_name: String,
514 pub config: ShortEndpointConfig,
516 #[schema(value_type = OutputEndpointMetrics)]
518 pub metrics: ExternalOutputEndpointMetrics,
519 pub fatal_error: Option<String>,
521 #[serde(default, skip_serializing_if = "Option::is_none")]
523 pub encode_errors: Option<Vec<ConnectorError>>,
524 #[serde(default, skip_serializing_if = "Option::is_none")]
526 pub transport_errors: Option<Vec<ConnectorError>>,
527 #[serde(default)]
529 pub health: Option<ConnectorHealth>,
530 #[serde(default)]
535 pub paused: bool,
536}
537
538#[derive(Debug, Default, Serialize, Deserialize, ToSchema)]
540#[schema(as = GlobalControllerMetrics)]
541pub struct ExternalGlobalControllerMetrics {
542 pub state: PipelineState,
544 pub bootstrap_in_progress: bool,
546 pub transaction_status: TransactionStatus,
548 #[schema(value_type = i64)]
550 pub transaction_id: TransactionId,
551 pub transaction_msecs: Option<u64>,
559 pub transaction_records: Option<u64>,
567 pub commit_progress: Option<CommitProgressSummary>,
569 #[schema(value_type = TransactionInitiators)]
571 pub transaction_initiators: ExternalTransactionInitiators,
572 pub concurrent_bootstrap_phase: ConcurrentBootstrapPhase,
574 pub concurrent_bootstrap_progress: Option<CommitProgressSummary>,
578 pub rss_bytes: u64,
580 pub memory_pressure: MemoryPressure,
582 pub memory_pressure_epoch: u64,
584 pub cpu_msecs: u64,
586 pub uptime_msecs: u64,
591 #[serde(with = "chrono::serde::ts_seconds")]
593 #[schema(value_type = u64)]
594 pub start_time: DateTime<Utc>,
595 pub incarnation_uuid: Uuid,
597 #[serde(with = "chrono::serde::ts_seconds")]
599 #[schema(value_type = u64)]
600 pub initial_start_time: DateTime<Utc>,
601 pub storage_bytes: u64,
603 pub storage_mb_secs: u64,
605 #[serde(default, skip_serializing_if = "Option::is_none")]
607 pub disk_total_bytes: Option<u64>,
608 #[serde(default, skip_serializing_if = "Option::is_none")]
610 pub disk_available_bytes: Option<u64>,
611 pub runtime_elapsed_msecs: u64,
613 pub buffered_input_records: u64,
615 pub buffered_input_bytes: u64,
617 pub total_input_records: u64,
619 pub total_input_bytes: u64,
621 pub total_processed_records: u64,
623 pub total_processed_bytes: u64,
625 pub total_completed_records: u64,
627 pub output_stall_msecs: u64,
637 #[schema(value_type = u64)]
646 pub total_initiated_steps: Step,
647 #[schema(value_type = u64)]
661 pub total_completed_steps: Step,
662 pub pipeline_complete: bool,
664 pub platform_version: String,
670 pub runtime_version: String,
676}
677
678#[derive(Debug, Deserialize, Serialize, ToSchema, Default)]
686#[schema(as = ControllerStatus)]
687pub struct ExternalControllerStatus {
688 #[schema(value_type = GlobalControllerMetrics)]
690 pub global_metrics: ExternalGlobalControllerMetrics,
691 pub suspend_error: Option<SuspendError>,
693 pub checkpoint_activity: Option<CheckpointActivity>,
696 pub permanent_checkpoint_errors: Option<Vec<PermanentSuspendError>>,
701 #[schema(value_type = Vec<InputEndpointStatus>)]
703 pub inputs: Vec<ExternalInputEndpointStatus>,
704 #[schema(value_type = Vec<OutputEndpointStatus>)]
706 pub outputs: Vec<ExternalOutputEndpointStatus>,
707 #[serde(default, skip_serializing_if = "Vec::is_empty")]
709 pub host_metrics: Vec<HostMetrics>,
710}
711
712#[derive(Debug, Default, Deserialize, Serialize, ToSchema)]
714pub struct HostMetrics {
715 #[serde(default, skip_serializing_if = "Option::is_none")]
717 pub disk_total_bytes: Option<u64>,
718 #[serde(default, skip_serializing_if = "Option::is_none")]
720 pub disk_available_bytes: Option<u64>,
721}
722
723impl From<&ExternalGlobalControllerMetrics> for HostMetrics {
724 fn from(metrics: &ExternalGlobalControllerMetrics) -> Self {
725 Self {
726 disk_total_bytes: metrics.disk_total_bytes,
727 disk_available_bytes: metrics.disk_available_bytes,
728 }
729 }
730}
731
732fn serialize_timestamp_micros<S>(
733 timestamp: &DateTime<Utc>,
734 serializer: S,
735) -> Result<S::Ok, S::Error>
736where
737 S: serde::Serializer,
738{
739 serializer.serialize_str(×tamp.to_rfc3339_opts(SecondsFormat::Micros, true))
740}
741
742#[cfg(test)]
743mod tests {
744 use super::ConnectorError;
745 use chrono::{DateTime, Utc};
746
747 #[test]
748 fn connector_error_timestamp_serializes_with_microsecond_precision() {
749 let error = ConnectorError {
750 timestamp: DateTime::parse_from_rfc3339("2026-03-08T05:26:42.442438448Z")
751 .unwrap()
752 .with_timezone(&Utc),
753 index: 1,
754 tag: None,
755 message: "boom".to_string(),
756 };
757
758 let json = serde_json::to_string(&error).unwrap();
759 assert!(json.contains(r#""timestamp":"2026-03-08T05:26:42.442438Z""#));
760 }
761
762 #[test]
763 fn output_metrics_batch_records_written_serializes() {
764 use super::ExternalOutputEndpointMetrics;
765
766 let metrics = ExternalOutputEndpointMetrics {
767 batch_records_written: Some(42),
768 ..Default::default()
769 };
770 let json = serde_json::to_string(&metrics).unwrap();
771 assert!(json.contains(r#""batch_records_written":42"#));
772
773 let deserialized: ExternalOutputEndpointMetrics = serde_json::from_str(&json).unwrap();
774 assert_eq!(deserialized.batch_records_written, Some(42));
775 }
776
777 #[test]
778 fn output_metrics_batch_records_written_defaults_to_none() {
779 use super::ExternalOutputEndpointMetrics;
780
781 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}"#;
783 let metrics: ExternalOutputEndpointMetrics = serde_json::from_str(json).unwrap();
784 assert_eq!(metrics.batch_records_written, None);
785 }
786
787 mod merge {
788 use chrono::{DateTime, TimeZone, Utc};
789
790 use crate::adapter_stats::{
791 CompletedWatermark, ConnectorError, ConnectorHealth, ConnectorHealthStatus,
792 ExternalInputEndpointMetrics, ExternalInputEndpointStatus, FrontierMerge,
793 ShortEndpointConfig,
794 };
795 use serde_json::{Value, json};
796
797 fn time(secs: i64) -> DateTime<Utc> {
798 Utc.timestamp_opt(secs, 0).unwrap()
799 }
800
801 fn error(secs: i64, message: &str) -> ConnectorError {
802 ConnectorError {
803 timestamp: time(secs),
804 index: 0,
805 tag: None,
806 message: message.into(),
807 }
808 }
809
810 fn frontier(ingested_secs: i64) -> CompletedWatermark {
811 CompletedWatermark {
812 metadata: serde_json::json!(ingested_secs),
813 ingested_at: time(ingested_secs),
814 processed_at: time(ingested_secs + 1),
815 completed_at: time(ingested_secs + 2),
816 }
817 }
818
819 fn status() -> ExternalInputEndpointStatus {
820 ExternalInputEndpointStatus {
821 endpoint_name: "t.kafka".into(),
822 config: ShortEndpointConfig { stream: "t".into() },
823 metrics: ExternalInputEndpointMetrics {
824 total_bytes: 10,
825 total_records: 1,
826 buffered_records: 2,
827 buffered_bytes: 20,
828 num_transport_errors: 3,
829 num_parse_errors: 4,
830 end_of_input: true,
831 processing_latency_p99_micros: Some(100),
832 },
833 fatal_error: None,
834 parse_errors: None,
835 transport_errors: None,
836 health: Some(ConnectorHealth::healthy()),
837 paused: false,
838 barrier: false,
839 completed_frontier: None,
840 }
841 }
842
843 #[test]
844 fn counters_add_up() {
845 let mut a = status();
846 let mut b = status();
847 b.metrics.processing_latency_p99_micros = Some(500);
848 b.metrics.end_of_input = false;
849 a.merge(b, FrontierMerge::Opaque);
850 let m = &a.metrics;
851 assert_eq!(
852 (
853 m.total_bytes,
854 m.total_records,
855 m.buffered_records,
856 m.buffered_bytes
857 ),
858 (20, 2, 4, 40)
859 );
860 assert_eq!((m.num_transport_errors, m.num_parse_errors), (6, 8));
861 assert!(!m.end_of_input);
862 assert_eq!(m.processing_latency_p99_micros, Some(500));
863 }
864
865 #[test]
866 fn worst_host_decides() {
867 let mut a = status();
868 let mut b = status();
869 b.fatal_error = Some("broken".into());
870 b.health = Some(ConnectorHealth::unhealthy("sick"));
871 b.barrier = true;
872 a.merge(b, FrontierMerge::Opaque);
873 assert_eq!(a.fatal_error.as_deref(), Some("broken"));
874 assert!(matches!(
875 a.health.unwrap().status,
876 ConnectorHealthStatus::Unhealthy
877 ));
878 assert!(a.barrier);
879
880 let mut a = status();
882 a.fatal_error = Some("first".into());
883 let mut b = status();
884 b.fatal_error = Some("second".into());
885 a.merge(b, FrontierMerge::Opaque);
886 assert_eq!(a.fatal_error.as_deref(), Some("first"));
887 }
888
889 fn merge_metadata(
893 hosts: Vec<(bool, Option<(i64, Value)>)>,
894 kind: FrontierMerge,
895 ) -> Option<(DateTime<Utc>, Value)> {
896 let mut statuses = hosts.into_iter().map(|(eoi, f)| {
897 let mut s = status();
898 s.metrics.end_of_input = eoi;
899 s.completed_frontier = f.map(|(secs, metadata)| CompletedWatermark {
900 metadata,
901 ..frontier(secs)
902 });
903 s
904 });
905 let mut x = statuses.next().unwrap();
906 statuses.for_each(|y| x.merge(y, kind));
907 x.completed_frontier.map(|f| (f.ingested_at, f.metadata))
908 }
909
910 #[test]
913 fn shared_frontier_merge() {
914 let merged = |hosts| merge_metadata(hosts, FrontierMerge::Shared);
915 let version = |v: i64| json!({"version": v});
916 assert_eq!(
917 merged(vec![
918 (false, Some((10, version(3)))),
919 (false, Some((5, version(2))))
920 ]),
921 Some((time(5), version(2)))
922 );
923 assert_eq!(
924 merged(vec![
925 (true, Some((5, version(2)))),
926 (false, Some((10, version(7))))
927 ]),
928 Some((time(10), version(7)))
929 );
930 assert_eq!(
931 merged(vec![
932 (true, Some((5, version(2)))),
933 (true, Some((10, version(2))))
934 ]),
935 Some((time(10), version(2)))
936 );
937 }
938
939 #[test]
942 fn partitioned_frontier_merge() {
943 let merged = |hosts| merge_metadata(hosts, FrontierMerge::Partitioned);
944 let host = |partitions: &[i64], offsets: &[i64]| json!({"partitions": partitions, "offsets": offsets, "shard": {"host": 0}});
946 let joined = |partitions: &[i64], offsets: &[i64]| json!({"partitions": partitions, "offsets": offsets});
947
948 assert_eq!(
950 merged(vec![
951 (false, Some((10, host(&[1, 4], &[11, 14])))),
952 (false, Some((5, host(&[2], &[12])))),
953 (false, Some((7, host(&[0, 3], &[10, 13])))),
954 ]),
955 Some((time(5), joined(&[0, 1, 2, 3, 4], &[10, 11, 12, 13, 14])))
956 );
957
958 assert_eq!(
960 merged(vec![
961 (true, Some((5, host(&[1], &[11])))),
962 (false, Some((10, host(&[0], &[10])))),
963 ]),
964 Some((time(10), joined(&[0, 1], &[10, 11])))
965 );
966 assert_eq!(
967 merged(vec![
968 (true, Some((10, host(&[1], &[11])))),
969 (true, Some((5, host(&[0], &[10])))),
970 ]),
971 Some((time(10), joined(&[0, 1], &[10, 11])))
972 );
973
974 assert_eq!(
977 merged(vec![(true, None), (false, Some((10, host(&[0], &[10]))))]),
978 Some((time(10), joined(&[0], &[10])))
979 );
980
981 assert_eq!(
983 merged(vec![(false, None), (true, Some((10, host(&[0], &[10]))))]),
984 None
985 );
986
987 for other in [json!({"offsets": [11]}), host(&[0], &[11]), Value::Null] {
990 assert_eq!(
991 merged(vec![
992 (false, Some((10, host(&[0], &[10])))),
993 (false, Some((5, other.clone()))),
994 ]),
995 Some((time(5), Value::Null)),
996 "{other}"
997 );
998 }
999 }
1000
1001 #[test]
1003 fn pause_merge() {
1004 let merged = |hosts: &[bool]| {
1005 let mut statuses = hosts.iter().map(|&paused| {
1006 let mut s = status();
1007 s.paused = paused;
1008 s
1009 });
1010 let mut x = statuses.next().unwrap();
1011 statuses.for_each(|y| x.merge(y, FrontierMerge::Opaque));
1012 x.paused
1013 };
1014 assert!(merged(&[true, true, true]));
1015 assert!(!merged(&[false, false, false]));
1016 for hosts in [
1017 [true, false, false],
1018 [false, true, false],
1019 [false, false, true],
1020 [true, true, false],
1021 [false, true, true],
1022 [true, false, true],
1023 ] {
1024 assert!(!merged(&hosts), "{hosts:?}");
1025 }
1026 }
1027
1028 #[test]
1029 fn errors_are_combined_in_time_order() {
1030 let mut a = status();
1031 a.parse_errors = Some(vec![error(1, "a1"), error(5, "a5")]);
1032 let mut b = status();
1033 b.parse_errors = Some(vec![error(3, "b3")]);
1034 b.transport_errors = Some(vec![error(2, "b2")]);
1035 a.merge(b, FrontierMerge::Opaque);
1036 let messages = |errors: &Option<Vec<ConnectorError>>| {
1037 errors
1038 .iter()
1039 .flatten()
1040 .map(|e| e.message.clone())
1041 .collect::<Vec<_>>()
1042 };
1043 assert_eq!(messages(&a.parse_errors), ["a1", "b3", "a5"]);
1044 assert_eq!(messages(&a.transport_errors), ["b2"]);
1045 }
1046
1047 #[test]
1048 fn opaque_frontier_merge() {
1049 let merged = |hosts: &[(bool, Option<i64>)]| {
1052 let mut statuses = hosts.iter().map(|&(eoi, f)| {
1053 let mut s = status();
1054 s.metrics.end_of_input = eoi;
1055 s.completed_frontier = f.map(frontier);
1056 s
1057 });
1058 let mut x = statuses.next().unwrap();
1059 statuses.for_each(|y| x.merge(y, FrontierMerge::Opaque));
1060 x.completed_frontier
1061 .map(|f| (f.ingested_at, !f.metadata.is_null()))
1062 };
1063 let (busy, done) = (false, true);
1064
1065 assert_eq!(
1067 merged(&[(busy, Some(10)), (busy, Some(5))]),
1068 Some((time(5), false))
1069 );
1070 assert_eq!(
1071 merged(&[(busy, Some(5)), (busy, Some(10))]),
1072 Some((time(5), false))
1073 );
1074
1075 assert_eq!(merged(&[(busy, None), (busy, Some(10))]), None);
1078 assert_eq!(merged(&[(busy, Some(10)), (busy, None)]), None);
1079 assert_eq!(
1080 merged(&[(busy, Some(10)), (busy, None), (busy, Some(5))]),
1081 None
1082 );
1083 assert_eq!(
1084 merged(&[(busy, None), (done, Some(5)), (busy, Some(10))]),
1085 None
1086 );
1087
1088 assert_eq!(
1092 merged(&[(busy, Some(10)), (done, Some(5))]),
1093 Some((time(10), true))
1094 );
1095 assert_eq!(
1096 merged(&[(done, Some(5)), (busy, Some(10))]),
1097 Some((time(10), true))
1098 );
1099 assert_eq!(
1100 merged(&[(done, None), (busy, Some(10))]),
1101 Some((time(10), true))
1102 );
1103 assert_eq!(
1104 merged(&[(busy, Some(10)), (done, None)]),
1105 Some((time(10), true))
1106 );
1107 assert_eq!(
1108 merged(&[(done, Some(5)), (busy, Some(10)), (done, Some(20))]),
1109 Some((time(10), true))
1110 );
1111 assert_eq!(
1112 merged(&[(done, Some(5)), (busy, Some(10)), (busy, Some(20))]),
1113 Some((time(10), false))
1114 );
1115
1116 assert_eq!(
1118 merged(&[(done, Some(10)), (done, Some(5))]),
1119 Some((time(10), true))
1120 );
1121 assert_eq!(
1122 merged(&[(done, None), (done, Some(5))]),
1123 Some((time(5), true))
1124 );
1125 assert_eq!(merged(&[(done, None), (done, None)]), None);
1126 }
1127 }
1128}