1use std::sync::LazyLock;
2use std::time::Duration;
3
4use async_trait::async_trait;
5use datadog_protos::checks::{
6 check_data::Data,
7 checks_server::{Checks, ChecksServer},
8 event::{AlertType as ProtoAlertType, Event as ProtoEvent, Priority as ProtoPriority},
9 log::{Log as ProtoLog, LogLevel},
10 metric::{Metric as ProtoMetric, MetricType},
11 service_check::{ServiceCheck as ProtoServiceCheck, Status as ServiceCheckStatus},
12 SendCheckPayloadRequest, SendCheckPayloadResponse,
13};
14use saluki_common::time::get_unix_timestamp_nanos;
15use saluki_core::{
16 accounting::{MemoryBounds, MemoryBoundsBuilder},
17 components::{sources::*, BuildContext},
18 data_model::{
19 event::{
20 eventd::{AlertType, EventD, Priority},
21 log::Log,
22 metric::{context::Context, Metric},
23 service_check::{CheckStatus, ServiceCheck},
24 Event, EventType,
25 },
26 tags::{Tag, TagSet},
27 },
28 runtime,
29 topology::OutputDefinition,
30};
31use saluki_error::{generic_error, GenericError};
32use saluki_io::net::{
33 server::http::{Http2Config, HttpServer},
34 ListenAddress,
35};
36use stringtheory::MetaString;
37use tokio::select;
38use tokio::sync::mpsc;
39use tonic::{Response, Status};
40use tracing::{debug, trace, warn};
41
42#[derive(Debug)]
44pub struct ChecksIPCConfiguration {
45 default_hostname: MetaString,
46 grpc_endpoint: ListenAddress,
47}
48
49impl ChecksIPCConfiguration {
50 pub fn new(grpc_endpoint: ListenAddress, default_hostname: impl Into<MetaString>) -> Self {
52 Self {
53 default_hostname: default_hostname.into(),
54 grpc_endpoint,
55 }
56 }
57}
58
59#[async_trait]
60impl SourceBuilder for ChecksIPCConfiguration {
61 fn outputs(&self) -> &[OutputDefinition<EventType>] {
62 static OUTPUTS: LazyLock<Vec<OutputDefinition<EventType>>> = LazyLock::new(|| {
63 vec![
64 OutputDefinition::named_output("metrics", EventType::Metric),
65 OutputDefinition::named_output("logs", EventType::Log),
66 OutputDefinition::named_output("events", EventType::EventD),
67 OutputDefinition::named_output("service_checks", EventType::ServiceCheck),
68 ]
69 });
70
71 &OUTPUTS
72 }
73
74 async fn build(&self, _context: BuildContext) -> Result<Box<dyn Source + Send>, GenericError> {
75 Ok(Box::new(ChecksIPC {
76 grpc_endpoint: self.grpc_endpoint.clone(),
77 default_hostname: self.default_hostname.clone(),
78 }))
79 }
80}
81
82impl MemoryBounds for ChecksIPCConfiguration {
83 fn specify_bounds(&self, builder: &mut MemoryBoundsBuilder) {
84 builder.minimum().with_single_value::<ChecksIPC>("checks_ipc");
86 }
87}
88
89struct ChecksIPC {
90 grpc_endpoint: ListenAddress,
91 default_hostname: MetaString,
92}
93
94#[async_trait]
95impl Source for ChecksIPC {
96 async fn run(self: Box<Self>, mut context: SourceContext) -> Result<(), GenericError> {
97 let ChecksIPC {
98 grpc_endpoint,
99 default_hostname,
100 } = *self;
101
102 let mut health = context.take_health_handle();
103
104 let (events_tx, mut events_rx) = mpsc::channel(16);
105
106 let ListenAddress::Tcp(grpc_socket_addr) = grpc_endpoint else {
107 return Err(generic_error!("Checks IPC gRPC endpoint must be a TCP address."));
108 };
109
110 let grpc_server = HttpServer::from_listen_address(ListenAddress::Tcp(grpc_socket_addr))
113 .add_grpc_service(ChecksServer::new(ChecksService {
114 events_tx,
115 default_hostname,
116 }))
117 .with_http2_only()
118 .with_http2_config(Http2Config::grpc_defaults())
119 .with_worker_pool(context.topology_context().global_thread_pool().clone());
120
121 runtime::nested_supervisor(grpc_server.into_supervisor())
124 .needed()
125 .stops_with_owner()
126 .spawn();
127
128 health.mark_ready();
129 debug!("Checks IPC source started.");
130
131 loop {
132 select! {
133 _ = health.live() => continue,
134 maybe_event = events_rx.recv() => {
135 let Some(event) = maybe_event else {
136 break;
137 };
138
139 let output_name = match &event {
140 Event::Metric(_) => "metrics",
141 Event::Log(_) => "logs",
142 Event::EventD(_) => "events",
143 Event::ServiceCheck(_) => "service_checks",
144 _ => continue,
145 };
146
147 if let Err(e) = context.dispatcher().dispatch_one_named(output_name, event).await {
148 warn!("Failed to dispatch {output_name} event: {:?}", e);
149 }
150 },
151 }
152 }
153
154 debug!("Checks IPC source stopped.");
155 Ok(())
156 }
157}
158
159struct ChecksService {
160 events_tx: mpsc::Sender<Event>,
161 default_hostname: MetaString,
162}
163
164#[async_trait]
165impl Checks for ChecksService {
166 async fn send_check_payload(
167 &self, request: tonic::Request<SendCheckPayloadRequest>,
168 ) -> Result<Response<SendCheckPayloadResponse>, Status> {
169 trace!("Received check payload.");
170
171 let payload = request.into_inner();
172 for check_data in payload.data.into_iter().filter_map(|data| data.data) {
173 let Some(event) = check_data_to_event(check_data, &self.default_hostname) else {
174 continue;
175 };
176
177 if let Err(e) = self.events_tx.send(event).await {
178 warn!("Failed to send check event: {:?}", e);
179 }
180 }
181
182 Ok(Response::new(SendCheckPayloadResponse {}))
183 }
184}
185
186fn check_data_to_event(check_data: Data, default_hostname: &MetaString) -> Option<Event> {
187 match check_data {
190 Data::Metric(metric) => {
191 let ProtoMetric {
192 r#type,
193 name,
194 value,
195 timestamp,
196 tags,
197 hostname,
198 interval_secs,
199 } = metric;
200
201 let metric_type = MetricType::try_from(r#type).ok()?;
202
203 let tags = tags.into_iter().map(Tag::from).collect::<TagSet>();
204 let mut context = Context::from_parts(name, tags.into_shared());
205 let hostname = if hostname.is_empty() {
206 default_hostname.clone()
207 } else {
208 MetaString::from(hostname)
209 };
210 context = context.with_host(Some(hostname));
211 let metric = match metric_type {
212 MetricType::Counter => Metric::counter(context, (timestamp, value)),
213 MetricType::Gauge => Metric::gauge(context, (timestamp, value)),
214 MetricType::Rate => {
215 if interval_secs == 0 {
216 warn!("Received rate metric from check with interval of zero. Skipping.");
217 return None;
218 }
219 Metric::rate(context, (timestamp, value), Duration::from_secs(interval_secs))
220 }
221 MetricType::Histogram => Metric::histogram(context, (timestamp, value)),
222 MetricType::Unspecified => {
223 warn!("Received metric with unspecified type. Skipping.");
224 return None;
225 }
226 };
227 Some(Event::Metric(metric))
228 }
229 Data::Log(log) => {
230 let ProtoLog { message, level } = log;
231
232 let level = LogLevel::try_from(level).ok()?;
233 let status = log_level_to_log_status(level);
234
235 Some(Event::Log(
236 Log::new(message)
237 .with_status(status)
238 .with_ingestion_timestamp(get_unix_timestamp_nanos()),
239 ))
240 }
241 Data::Event(event) => {
242 let ProtoEvent {
243 title,
244 text,
245 priority,
246 hostname,
247 tags,
248 alert_type,
249 aggregation_key,
250 source_type_name,
251 timestamp,
252 } = event;
253
254 let tags = tags.into_iter().map(Tag::from).collect::<TagSet>();
255 let mut eventd = EventD::new(title, text)
256 .with_timestamp(timestamp)
257 .with_tags(tags.into_shared());
258
259 if !hostname.is_empty() {
260 eventd.set_hostname(MetaString::from(hostname));
261 }
262 if !aggregation_key.is_empty() {
263 eventd.set_aggregation_key(MetaString::from(aggregation_key));
264 }
265 if !source_type_name.is_empty() {
266 eventd.set_source_type_name(MetaString::from(source_type_name));
267 }
268 if let Some(p) = ProtoPriority::try_from(priority)
269 .ok()
270 .and_then(proto_priority_to_priority)
271 {
272 eventd.set_priority(p);
273 }
274 if let Some(a) = ProtoAlertType::try_from(alert_type)
275 .ok()
276 .and_then(proto_alert_type_to_alert_type)
277 {
278 eventd.set_alert_type(a);
279 }
280 Some(Event::EventD(eventd))
281 }
282 Data::ServiceCheck(sc) => {
283 let ProtoServiceCheck {
284 status,
285 name,
286 message,
287 tags,
288 hostname,
289 } = sc;
290
291 let Some(status) = ServiceCheckStatus::try_from(status)
292 .ok()
293 .and_then(service_check_status_to_check_status)
294 else {
295 warn!(
296 "Received service check with unspecified or invalid status: {}. Skipping.",
297 status
298 );
299 return None;
300 };
301 let tags = tags.into_iter().map(Tag::from).collect::<TagSet>();
302 let mut service_check = ServiceCheck::new(name, status)
303 .with_message(MetaString::from(message))
304 .with_tags(tags.into_shared());
305 if !hostname.is_empty() {
306 service_check.set_hostname(MetaString::from(hostname));
307 }
308 Some(Event::ServiceCheck(service_check))
309 }
310 }
311}
312
313fn log_level_to_log_status(log_level: LogLevel) -> &'static str {
315 match log_level {
316 LogLevel::Trace => "trace",
317 LogLevel::Debug => "debug",
318 LogLevel::Info => "info",
319 LogLevel::Warning => "warn",
320 LogLevel::Error => "error",
321 LogLevel::Critical => "emergency",
322 _ => "info",
323 }
324}
325
326fn service_check_status_to_check_status(status: ServiceCheckStatus) -> Option<CheckStatus> {
327 match status {
328 ServiceCheckStatus::Ok => Some(CheckStatus::Ok),
329 ServiceCheckStatus::Warning => Some(CheckStatus::Warning),
330 ServiceCheckStatus::Critical => Some(CheckStatus::Critical),
331 ServiceCheckStatus::Unknown => Some(CheckStatus::Unknown),
332 ServiceCheckStatus::Unspecified => None,
333 }
334}
335
336fn proto_priority_to_priority(priority: ProtoPriority) -> Option<Priority> {
337 match priority {
338 ProtoPriority::Normal => Some(Priority::Normal),
339 ProtoPriority::Low => Some(Priority::Low),
340 ProtoPriority::Unspecified => None,
341 }
342}
343
344fn proto_alert_type_to_alert_type(alert_type: ProtoAlertType) -> Option<AlertType> {
345 match alert_type {
346 ProtoAlertType::Info => Some(AlertType::Info),
347 ProtoAlertType::Error => Some(AlertType::Error),
348 ProtoAlertType::Warning => Some(AlertType::Warning),
349 ProtoAlertType::Success => Some(AlertType::Success),
350 ProtoAlertType::Unspecified => None,
351 }
352}
353
354#[cfg(test)]
355mod logs_on_the_wire;
356
357#[cfg(test)]
358mod tests {
359 use std::num::NonZeroUsize;
360
361 use datadog_protos::checks::{
362 check_data::Data,
363 checks_client::ChecksClient,
364 event::Event as ProtoEvent,
365 log::Log as ProtoLog,
366 metric::{Metric as ProtoMetric, MetricType as ProtoMetricType},
367 service_check::{ServiceCheck as ProtoServiceCheck, Status as ProtoServiceCheckStatus},
368 CheckData,
369 };
370 use saluki_core::components::test_util::TestComponentDriver;
371 use saluki_core::data_model::event::metric::MetricValues;
372
373 use super::*;
374
375 fn metric_data(
376 r#type: i32, name: &str, value: f64, timestamp: u64, interval_secs: u64, tags: &[&str], hostname: &str,
377 ) -> Data {
378 Data::Metric(ProtoMetric {
379 r#type,
380 name: name.to_string(),
381 value,
382 timestamp,
383 tags: tags.iter().map(|t| (*t).to_string()).collect(),
384 hostname: hostname.to_string(),
385 interval_secs,
386 })
387 }
388
389 fn log_data(level: i32, message: &str) -> Data {
390 Data::Log(ProtoLog {
391 message: message.to_string(),
392 level,
393 })
394 }
395
396 fn event_data(title: &str, text: &str, timestamp: u64, tags: &[&str], hostname: &str) -> Data {
397 Data::Event(ProtoEvent {
398 title: title.to_string(),
399 text: text.to_string(),
400 priority: 0,
401 hostname: hostname.to_string(),
402 tags: tags.iter().map(|t| (*t).to_string()).collect(),
403 alert_type: 0,
404 aggregation_key: String::new(),
405 source_type_name: String::new(),
406 timestamp,
407 })
408 }
409
410 fn service_check_data(status: i32, name: &str, message: &str, tags: &[&str], hostname: &str) -> Data {
411 Data::ServiceCheck(ProtoServiceCheck {
412 status,
413 name: name.to_string(),
414 message: message.to_string(),
415 tags: tags.iter().map(|t| (*t).to_string()).collect(),
416 hostname: hostname.to_string(),
417 })
418 }
419
420 fn check_data_to_event_for_tests(check_data: Data) -> Option<Event> {
421 check_data_to_event(check_data, &MetaString::from_static("default-host"))
422 }
423
424 #[test]
425 fn metric_counter_conversion() {
426 let event = check_data_to_event_for_tests(metric_data(
427 ProtoMetricType::Counter as i32,
428 "my_counter",
429 1.0,
430 1234,
431 0,
432 &["tag1:value1", "tag2:value2"],
433 "",
434 ))
435 .expect("counter should convert");
436
437 let Event::Metric(metric) = event else {
438 panic!("expected Metric event");
439 };
440 assert_eq!(metric.context().name().as_ref(), "my_counter");
441 assert!(metric.context().tags().has_tag("tag1:value1"));
442 assert!(metric.context().tags().has_tag("tag2:value2"));
443 assert!(matches!(metric.values(), MetricValues::Counter(_)));
444 }
445
446 #[test]
447 fn metric_gauge_conversion() {
448 let event = check_data_to_event_for_tests(metric_data(
449 ProtoMetricType::Gauge as i32,
450 "my_gauge",
451 42.0,
452 1234,
453 0,
454 &[],
455 "",
456 ))
457 .expect("gauge should convert");
458 let Event::Metric(metric) = event else {
459 panic!("expected Metric event");
460 };
461 assert!(matches!(metric.values(), MetricValues::Gauge(_)));
462 }
463
464 #[test]
465 fn metric_histogram_conversion() {
466 let event = check_data_to_event_for_tests(metric_data(
467 ProtoMetricType::Histogram as i32,
468 "my_hist",
469 1.0,
470 1234,
471 0,
472 &[],
473 "",
474 ))
475 .expect("histogram should convert");
476 let Event::Metric(metric) = event else {
477 panic!("expected Metric event");
478 };
479 assert!(matches!(metric.values(), MetricValues::Histogram(_)));
480 }
481
482 #[test]
483 fn metric_rate_conversion_uses_interval() {
484 let event = check_data_to_event_for_tests(metric_data(
485 ProtoMetricType::Rate as i32,
486 "my_rate",
487 10.0,
488 1234,
489 60,
490 &[],
491 "",
492 ))
493 .expect("rate should convert");
494 let Event::Metric(metric) = event else {
495 panic!("expected Metric event");
496 };
497 match metric.values() {
498 MetricValues::Rate(_, interval) => assert_eq!(*interval, Duration::from_secs(60)),
499 other => panic!("expected Rate values, got {other:?}"),
500 }
501 }
502
503 #[test]
504 fn metric_rate_with_zero_interval_is_skipped() {
505 let event = check_data_to_event_for_tests(metric_data(
506 ProtoMetricType::Rate as i32,
507 "my_rate",
508 10.0,
509 1234,
510 0,
511 &[],
512 "",
513 ));
514 assert!(event.is_none(), "rate with zero interval must be skipped");
515 }
516
517 #[test]
518 fn metric_unspecified_type_is_skipped() {
519 let event = check_data_to_event_for_tests(metric_data(
520 ProtoMetricType::Unspecified as i32,
521 "x",
522 1.0,
523 1234,
524 0,
525 &[],
526 "",
527 ));
528 assert!(event.is_none(), "unspecified metric type must be skipped");
529 }
530
531 #[test]
532 fn metric_unknown_type_is_skipped() {
533 let event = check_data_to_event_for_tests(metric_data(99, "x", 1.0, 1234, 0, &[], ""));
535 assert!(event.is_none(), "unknown metric type must be skipped");
536 }
537
538 #[test]
539 fn log_unknown_level_is_skipped() {
540 let event = check_data_to_event_for_tests(log_data(99, "hello"));
542 assert!(event.is_none(), "unknown log level must be skipped");
543 }
544
545 #[test]
546 fn event_conversion_preserves_fields() {
547 let event = check_data_to_event_for_tests(event_data("title", "body", 1234, &["env:prod", "team:foo"], ""))
548 .expect("event should convert");
549 let Event::EventD(ev) = event else {
550 panic!("expected EventD event");
551 };
552 assert_eq!(ev.title(), "title");
553 assert_eq!(ev.text(), "body");
554 assert_eq!(ev.timestamp(), Some(1234));
555 assert!(ev.tags().has_tag("env:prod"));
556 assert!(ev.tags().has_tag("team:foo"));
557 }
558
559 #[test]
560 fn service_check_status_mapping() {
561 let cases = [
562 (ProtoServiceCheckStatus::Ok, CheckStatus::Ok),
563 (ProtoServiceCheckStatus::Warning, CheckStatus::Warning),
564 (ProtoServiceCheckStatus::Critical, CheckStatus::Critical),
565 (ProtoServiceCheckStatus::Unknown, CheckStatus::Unknown),
566 ];
567
568 for (proto_status, expected) in cases {
569 let event = check_data_to_event_for_tests(service_check_data(proto_status as i32, "n", "m", &[], ""))
570 .unwrap_or_else(|| panic!("status {proto_status:?} should convert"));
571 let Event::ServiceCheck(sc) = event else {
572 panic!("expected ServiceCheck event for {proto_status:?}");
573 };
574 assert_eq!(sc.status(), expected, "status {proto_status:?}");
575 }
576 }
577
578 #[test]
579 fn service_check_unspecified_status_is_skipped() {
580 let event = check_data_to_event_for_tests(service_check_data(
581 ProtoServiceCheckStatus::Unspecified as i32,
582 "n",
583 "m",
584 &[],
585 "",
586 ));
587 assert!(event.is_none(), "service check with unspecified status must be skipped");
588 }
589
590 #[test]
591 fn service_check_unknown_status_value_is_skipped() {
592 let event = check_data_to_event_for_tests(service_check_data(99, "n", "m", &[], ""));
594 assert!(
595 event.is_none(),
596 "service check with out-of-range status must be skipped"
597 );
598 }
599
600 #[test]
601 fn service_check_preserves_name_message_and_tags() {
602 let event = check_data_to_event_for_tests(service_check_data(
603 ProtoServiceCheckStatus::Ok as i32,
604 "my.check",
605 "all good",
606 &["env:prod"],
607 "",
608 ))
609 .expect("service check should convert");
610 let Event::ServiceCheck(sc) = event else {
611 panic!("expected ServiceCheck event");
612 };
613 assert_eq!(sc.name(), "my.check");
614 assert_eq!(sc.status(), CheckStatus::Ok);
615 assert_eq!(sc.message(), Some("all good"));
616 assert!(sc.tags().has_tag("env:prod"));
617 }
618
619 #[test]
620 fn metric_hostname_propagates() {
621 let event = check_data_to_event_for_tests(metric_data(
622 ProtoMetricType::Counter as i32,
623 "n",
624 1.0,
625 0,
626 0,
627 &[],
628 "host-a",
629 ))
630 .expect("metric should convert");
631 let Event::Metric(m) = event else {
632 panic!("expected Metric event");
633 };
634 assert_eq!(m.context().host(), Some("host-a"));
635 }
636
637 #[test]
638 fn metric_empty_hostname_uses_default_host() {
639 let event =
640 check_data_to_event_for_tests(metric_data(ProtoMetricType::Counter as i32, "n", 1.0, 0, 0, &[], ""))
641 .expect("metric should convert");
642 let Event::Metric(m) = event else {
643 panic!("expected Metric event");
644 };
645 assert_eq!(m.context().host(), Some("default-host"));
646 }
647
648 #[test]
649 fn eventd_hostname_propagates() {
650 let event =
651 check_data_to_event_for_tests(event_data("title", "body", 0, &[], "host-b")).expect("event should convert");
652 let Event::EventD(ev) = event else {
653 panic!("expected EventD event");
654 };
655 assert_eq!(ev.hostname(), Some("host-b"));
656 }
657
658 #[test]
659 fn eventd_empty_hostname_stays_unset() {
660 let event =
661 check_data_to_event_for_tests(event_data("title", "body", 0, &[], "")).expect("event should convert");
662 let Event::EventD(ev) = event else {
663 panic!("expected EventD event");
664 };
665 assert_eq!(ev.hostname(), None);
666 }
667
668 #[test]
669 fn service_check_hostname_propagates() {
670 let event = check_data_to_event_for_tests(service_check_data(
671 ProtoServiceCheckStatus::Ok as i32,
672 "n",
673 "m",
674 &[],
675 "host-c",
676 ))
677 .expect("service check should convert");
678 let Event::ServiceCheck(sc) = event else {
679 panic!("expected ServiceCheck event");
680 };
681 assert_eq!(sc.hostname(), Some("host-c"));
682 }
683
684 #[test]
685 fn service_check_empty_hostname_stays_unset() {
686 let event = check_data_to_event_for_tests(service_check_data(
687 ProtoServiceCheckStatus::Ok as i32,
688 "n",
689 "m",
690 &[],
691 "",
692 ))
693 .expect("service check should convert");
694 let Event::ServiceCheck(sc) = event else {
695 panic!("expected ServiceCheck event");
696 };
697 assert_eq!(sc.hostname(), None);
698 }
699
700 #[test]
701 fn eventd_priority_propagates() {
702 let event = check_data_to_event_for_tests(Data::Event(ProtoEvent {
703 priority: ProtoPriority::Low as i32,
704 ..Default::default()
705 }))
706 .expect("event should convert");
707 let Event::EventD(ev) = event else {
708 panic!("expected EventD event");
709 };
710 assert_eq!(ev.priority(), Some(Priority::Low));
711 }
712
713 #[test]
714 fn eventd_alert_type_propagates() {
715 let event = check_data_to_event_for_tests(Data::Event(ProtoEvent {
716 alert_type: ProtoAlertType::Warning as i32,
717 ..Default::default()
718 }))
719 .expect("event should convert");
720 let Event::EventD(ev) = event else {
721 panic!("expected EventD event");
722 };
723 assert_eq!(ev.alert_type(), Some(AlertType::Warning));
724 }
725
726 #[test]
727 fn eventd_aggregation_key_propagates() {
728 let event = check_data_to_event_for_tests(Data::Event(ProtoEvent {
729 aggregation_key: "agg-key-1".to_string(),
730 ..Default::default()
731 }))
732 .expect("event should convert");
733 let Event::EventD(ev) = event else {
734 panic!("expected EventD event");
735 };
736 assert_eq!(ev.aggregation_key(), Some("agg-key-1"));
737 }
738
739 #[test]
740 fn eventd_source_type_name_propagates() {
741 let event = check_data_to_event_for_tests(Data::Event(ProtoEvent {
742 source_type_name: "my-source".to_string(),
743 ..Default::default()
744 }))
745 .expect("event should convert");
746 let Event::EventD(ev) = event else {
747 panic!("expected EventD event");
748 };
749 assert_eq!(ev.source_type_name(), Some("my-source"));
750 }
751
752 #[test]
753 fn eventd_unspecified_proto_keeps_saluki_defaults() {
754 let event = check_data_to_event_for_tests(Data::Event(ProtoEvent::default())).expect("event should convert");
759 let Event::EventD(ev) = event else {
760 panic!("expected EventD event");
761 };
762 assert_eq!(ev.priority(), Some(Priority::Normal));
763 assert_eq!(ev.alert_type(), Some(AlertType::Info));
764 assert_eq!(ev.aggregation_key(), None);
765 assert_eq!(ev.source_type_name(), None);
766 assert_eq!(ev.hostname(), None);
767 }
768
769 #[tokio::test]
770 async fn accepted_events_are_dispatched_before_the_source_stops() {
771 const METRICS: usize = 64;
773
774 let address = std::net::TcpListener::bind("127.0.0.1:0")
775 .and_then(|listener| listener.local_addr())
776 .expect("should reserve an ephemeral port");
777
778 let (mut control, mut outputs) = TestComponentDriver::options()
780 .with_interconnect_capacity(NonZeroUsize::MIN)
781 .source(ChecksIPCConfiguration::new(ListenAddress::Tcp(address), "test-host"))
782 .await
783 .expect("source should build");
784 let mut metrics = outputs.take_named_output("metrics");
785
786 let endpoint =
787 tonic::transport::Endpoint::from_shared(format!("http://{address}")).expect("endpoint should parse");
788 let channel = tokio::time::timeout(Duration::from_secs(5), async {
789 loop {
790 match endpoint.connect().await {
791 Ok(channel) => return channel,
792 Err(_) => tokio::time::sleep(Duration::from_millis(10)).await,
793 }
794 }
795 })
796 .await
797 .expect("the gRPC server should start listening");
798
799 let request = SendCheckPayloadRequest {
800 data: (0..METRICS)
801 .map(|i| CheckData {
802 data: Some(metric_data(
803 ProtoMetricType::Gauge as i32,
804 &format!("metric_{i}"),
805 1.0,
806 0,
807 0,
808 &[],
809 "",
810 )),
811 })
812 .collect(),
813 };
814 let response = tokio::spawn(async move { ChecksClient::new(channel).send_check_payload(request).await });
815
816 let first = metrics.next().await.expect("the first metric should arrive");
817 control.signal_shutdown();
818 let (result, rest) = tokio::join!(control.wait(), metrics.collect_events());
819 result.expect("source should stop cleanly");
820 response
821 .await
822 .expect("request task should not panic")
823 .expect("request should succeed");
824 assert_eq!(
825 first.len() + rest.len(),
826 METRICS,
827 "every accepted metric must be dispatched"
828 );
829 }
830}