You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@druid.apache.org by "abhishekrb19 (via GitHub)" <gi...@apache.org> on 2024/02/09 21:13:10 UTC

[PR] Clean up kafka emitter tests, add more validations and code coverage. (druid)

abhishekrb19 opened a new pull request, #15878:
URL: https://github.com/apache/druid/pull/15878

   The `KafkaEmitterTest` wasn't validating what events were sent, but simply the dropped counters, which aren't that useful. This patch adds that and cleans up so it's a bit easier to write unit tests.
   
   Additionally, this module has fewer tests, so folks often run into code coverage issues with this extension generally. Hopefully this patch addresses that too.
   
   <!--
   In each section, please describe design decisions made, including:
    - Choice of algorithms
    - Behavioral aspects. What configuration values are acceptable? How are corner cases and error conditions handled, such as when there are insufficient resources?
    - Class organization and design (how the logic is split between classes, inheritance, composition, design patterns)
    - Method organization and design (how the logic is split between methods, parameters and return types)
    - Naming (class, method, API, configuration, HTTP endpoint, names of emitted metrics)
   -->
   
   
   <!-- It's good to describe an alternative design (or mention an alternative name) for every design (or naming) decision point and compare the alternatives with the designs that you've implemented (or the names you've chosen) to highlight the advantages of the chosen designs and names. -->
   
   <!-- If there was a discussion of the design of the feature implemented in this PR elsewhere (e. g. a "Proposal" issue, any other issue, or a thread in the development mailing list), link to that discussion from this PR description and explain what have changed in your final design compared to your original proposal or the consensus version in the end of the discussion. If something hasn't changed since the original discussion, you can omit a detailed discussion of those aspects of the design here, perhaps apart from brief mentioning for the sake of readability of this PR description. -->
   
   <!-- Some of the aspects mentioned above may be omitted for simple and small changes. -->
   
   <!-- Give your best effort to summarize your changes in a couple of sentences aimed toward Druid users. 
   
   If your change doesn't have end user impact, you can skip this section.
   
   For tips about how to write a good release note, see [Release notes](https://github.com/apache/druid/blob/master/CONTRIBUTING.md#release-notes).
   
   -->
   <hr>
   
   <!-- Check the items by putting "x" in the brackets for the done things. Not all of these items apply to every PR. Remove the items which are not done or not relevant to the PR. None of the items from the checklist below are strictly necessary, but it would be very helpful if you at least self-review the PR. -->
   
   This PR has:
   
   - [x] been self-reviewed.
   - [x] added unit tests or modified existing tests to cover new code paths, ensuring the threshold for [code coverage](https://github.com/apache/druid/blob/master/dev/code-review/code-coverage.md) is met.
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] Clean up kafka emitter tests, add more validations and code coverage. (druid)

Posted by "TSFenwick (via GitHub)" <gi...@apache.org>.
TSFenwick commented on code in PR #15878:
URL: https://github.com/apache/druid/pull/15878#discussion_r1486549206


##########
extensions-contrib/kafka-emitter/src/test/java/org/apache/druid/emitter/kafka/KafkaEmitterTest.java:
##########
@@ -19,95 +19,459 @@
 
 package org.apache.druid.emitter.kafka;
 
+import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.datatype.joda.JodaModule;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
+import org.apache.druid.jackson.DefaultObjectMapper;
 import org.apache.druid.java.util.common.DateTimes;
+import org.apache.druid.java.util.common.StringUtils;
 import org.apache.druid.java.util.emitter.core.Event;
+import org.apache.druid.java.util.emitter.core.EventMap;
 import org.apache.druid.java.util.emitter.service.AlertEvent;
 import org.apache.druid.java.util.emitter.service.SegmentMetadataEvent;
 import org.apache.druid.java.util.emitter.service.ServiceMetricEvent;
 import org.apache.druid.server.QueryStats;
 import org.apache.druid.server.RequestLogLine;
 import org.apache.druid.server.log.DefaultRequestLogEventBuilderFactory;
-import org.apache.druid.server.log.RequestLogEvent;
 import org.apache.kafka.clients.producer.KafkaProducer;
 import org.apache.kafka.clients.producer.Producer;
+import org.apache.kafka.clients.producer.ProducerConfig;
+import org.apache.kafka.clients.producer.ProducerRecord;
+import org.junit.After;
 import org.junit.Assert;
+import org.junit.Before;
 import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
 
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
-import java.util.Set;
+import java.util.Map;
 import java.util.concurrent.CountDownLatch;
 
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
-@RunWith(Parameterized.class)
 public class KafkaEmitterTest
 {
-  @Parameterized.Parameter(0)
-  public Set<KafkaEmitterConfig.EventType> eventsType;
+  private KafkaProducer<String, String> producer;
 
-  @Parameterized.Parameter(1)
-  public String requestTopic;
+  @Before
+  public void setup()
+  {
+    producer = mock(KafkaProducer.class);
+  }
 
-  @Parameterized.Parameters(name = "{index}: eventTypes - {0}, requestTopic - {1}")
-  public static Object[] data()
+  @After
+  public void tearDown()
   {
-    return new Object[][] {
-        {new HashSet<>(Arrays.asList(KafkaEmitterConfig.EventType.METRICS, KafkaEmitterConfig.EventType.REQUESTS, KafkaEmitterConfig.EventType.ALERTS, KafkaEmitterConfig.EventType.SEGMENT_METADATA)), "requests"},
-        {new HashSet<>(Arrays.asList(KafkaEmitterConfig.EventType.METRICS, KafkaEmitterConfig.EventType.ALERTS, KafkaEmitterConfig.EventType.SEGMENT_METADATA)), null}
-    };
+    producer.close();
+  }
+
+  private static final ObjectMapper MAPPER = new DefaultObjectMapper();
+
+  private static final List<Event> SERVICE_METRIC_EVENTS = ImmutableList.of(
+      ServiceMetricEvent.builder().setMetric("m1", 1).build("service1", "host1"),
+      ServiceMetricEvent.builder().setMetric("m2", 100).build("service2", "host1"),
+      ServiceMetricEvent.builder().setMetric("m3", 200).build("service2", "host1"),
+      ServiceMetricEvent.builder().setMetric("m1", 150).build("service2", "host2"),
+      ServiceMetricEvent.builder().setMetric("m5", 250).build("service3", "host2")
+  );
+
+  private static final List<Event> ALERT_EVENTS = ImmutableList.of(
+      new AlertEvent("service1", "host1", "description"),
+      new AlertEvent("service2", "host2", "description")
+  );
+
+  private static final List<Event> REQUEST_LOG_EVENTS = ImmutableList.of(
+      DefaultRequestLogEventBuilderFactory.instance().createRequestLogEventBuilder(
+          "requests",
+          RequestLogLine.forSql(
+              "sql1", null, DateTimes.nowUtc(), null, new QueryStats(ImmutableMap.of())
+          )
+      ).build("service", "host"),
+      DefaultRequestLogEventBuilderFactory.instance().createRequestLogEventBuilder(
+          "requests",
+          RequestLogLine.forSql(
+              "sql2", null, DateTimes.nowUtc(), null, new QueryStats(ImmutableMap.of())
+          )
+      ).build("service", "host")
+  );
+
+  private static final List<Event> SEGMENT_METADATA_EVENTS = ImmutableList.of(
+      new SegmentMetadataEvent(
+          "ds1",
+          DateTimes.of("2001-01-01T00:00:00.000Z"),
+          DateTimes.of("2001-01-02T00:00:00.000Z"),
+          DateTimes.of("2001-01-03T00:00:00.000Z"),
+          "ds1",
+          true
+      ),
+      new SegmentMetadataEvent(
+          "ds2",
+          DateTimes.of("2020-01-01T00:00:00.000Z"),
+          DateTimes.of("2020-01-02T00:00:00.000Z"),
+          DateTimes.of("2020-01-03T00:00:00.000Z"),
+          "ds2",
+          true
+      )
+  );
+
+  private static final List<Event> UNKNOWN_EVENTS = ImmutableList.of(
+      new TestEvent(),
+      new TestEvent(),
+      new TestEvent()
+  );
+
+  @Test(timeout = 10_000)
+  public void testServiceMetricEvents() throws JsonProcessingException, InterruptedException
+  {
+    final KafkaEmitterConfig kafkaEmitterConfig = new KafkaEmitterConfig(
+        "",
+        new HashSet<>(Collections.singletonList(KafkaEmitterConfig.EventType.METRICS)),
+        "metrics",
+        "alerts",
+        "requests",
+        "segments",
+        "clusterName",
+        ImmutableMap.of("clusterId", "cluster-101"),
+        null,
+        null
+    );
+
+    final KafkaEmitter kafkaEmitter = initKafkaEmitter(kafkaEmitterConfig);
+
+    final List<Event> inputEvents = flattenEvents(SERVICE_METRIC_EVENTS);
+    final CountDownLatch eventLatch = new CountDownLatch(inputEvents.size());
+
+    final Map<String, List<String>> feedToExpectedEvents = trackExpectedEventsPerFeed(
+        inputEvents,
+        kafkaEmitterConfig.getClusterName(),
+        kafkaEmitterConfig.getExtraDimensions()
+    );
+    final Map<String, List<String>> feedToActualEvents = trackActualEventsPerFeed(eventLatch);
+
+    emitEvents(kafkaEmitter, inputEvents, eventLatch);
+
+    validateEvents(feedToExpectedEvents, feedToActualEvents);
+
+    Assert.assertEquals(0, kafkaEmitter.getMetricLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getAlertLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getSegmentMetadataLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getSegmentMetadataLostCount());

Review Comment:
   @abhishekrb19 typo error here? we have a double check on the same value



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] Clean up kafka emitter tests, add more validations and code coverage. (druid)

Posted by "TSFenwick (via GitHub)" <gi...@apache.org>.
TSFenwick commented on code in PR #15878:
URL: https://github.com/apache/druid/pull/15878#discussion_r1486554098


##########
extensions-contrib/kafka-emitter/src/test/java/org/apache/druid/emitter/kafka/KafkaEmitterTest.java:
##########
@@ -19,95 +19,459 @@
 
 package org.apache.druid.emitter.kafka;
 
+import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.datatype.joda.JodaModule;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
+import org.apache.druid.jackson.DefaultObjectMapper;
 import org.apache.druid.java.util.common.DateTimes;
+import org.apache.druid.java.util.common.StringUtils;
 import org.apache.druid.java.util.emitter.core.Event;
+import org.apache.druid.java.util.emitter.core.EventMap;
 import org.apache.druid.java.util.emitter.service.AlertEvent;
 import org.apache.druid.java.util.emitter.service.SegmentMetadataEvent;
 import org.apache.druid.java.util.emitter.service.ServiceMetricEvent;
 import org.apache.druid.server.QueryStats;
 import org.apache.druid.server.RequestLogLine;
 import org.apache.druid.server.log.DefaultRequestLogEventBuilderFactory;
-import org.apache.druid.server.log.RequestLogEvent;
 import org.apache.kafka.clients.producer.KafkaProducer;
 import org.apache.kafka.clients.producer.Producer;
+import org.apache.kafka.clients.producer.ProducerConfig;
+import org.apache.kafka.clients.producer.ProducerRecord;
+import org.junit.After;
 import org.junit.Assert;
+import org.junit.Before;
 import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
 
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
-import java.util.Set;
+import java.util.Map;
 import java.util.concurrent.CountDownLatch;
 
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
-@RunWith(Parameterized.class)
 public class KafkaEmitterTest
 {
-  @Parameterized.Parameter(0)
-  public Set<KafkaEmitterConfig.EventType> eventsType;
+  private KafkaProducer<String, String> producer;
 
-  @Parameterized.Parameter(1)
-  public String requestTopic;
+  @Before
+  public void setup()
+  {
+    producer = mock(KafkaProducer.class);
+  }
 
-  @Parameterized.Parameters(name = "{index}: eventTypes - {0}, requestTopic - {1}")
-  public static Object[] data()
+  @After
+  public void tearDown()
   {
-    return new Object[][] {
-        {new HashSet<>(Arrays.asList(KafkaEmitterConfig.EventType.METRICS, KafkaEmitterConfig.EventType.REQUESTS, KafkaEmitterConfig.EventType.ALERTS, KafkaEmitterConfig.EventType.SEGMENT_METADATA)), "requests"},
-        {new HashSet<>(Arrays.asList(KafkaEmitterConfig.EventType.METRICS, KafkaEmitterConfig.EventType.ALERTS, KafkaEmitterConfig.EventType.SEGMENT_METADATA)), null}
-    };
+    producer.close();
+  }
+
+  private static final ObjectMapper MAPPER = new DefaultObjectMapper();
+
+  private static final List<Event> SERVICE_METRIC_EVENTS = ImmutableList.of(
+      ServiceMetricEvent.builder().setMetric("m1", 1).build("service1", "host1"),
+      ServiceMetricEvent.builder().setMetric("m2", 100).build("service2", "host1"),
+      ServiceMetricEvent.builder().setMetric("m3", 200).build("service2", "host1"),
+      ServiceMetricEvent.builder().setMetric("m1", 150).build("service2", "host2"),
+      ServiceMetricEvent.builder().setMetric("m5", 250).build("service3", "host2")
+  );
+
+  private static final List<Event> ALERT_EVENTS = ImmutableList.of(
+      new AlertEvent("service1", "host1", "description"),
+      new AlertEvent("service2", "host2", "description")
+  );
+
+  private static final List<Event> REQUEST_LOG_EVENTS = ImmutableList.of(
+      DefaultRequestLogEventBuilderFactory.instance().createRequestLogEventBuilder(
+          "requests",
+          RequestLogLine.forSql(
+              "sql1", null, DateTimes.nowUtc(), null, new QueryStats(ImmutableMap.of())
+          )
+      ).build("service", "host"),
+      DefaultRequestLogEventBuilderFactory.instance().createRequestLogEventBuilder(
+          "requests",
+          RequestLogLine.forSql(
+              "sql2", null, DateTimes.nowUtc(), null, new QueryStats(ImmutableMap.of())
+          )
+      ).build("service", "host")
+  );
+
+  private static final List<Event> SEGMENT_METADATA_EVENTS = ImmutableList.of(
+      new SegmentMetadataEvent(
+          "ds1",
+          DateTimes.of("2001-01-01T00:00:00.000Z"),
+          DateTimes.of("2001-01-02T00:00:00.000Z"),
+          DateTimes.of("2001-01-03T00:00:00.000Z"),
+          "ds1",
+          true
+      ),
+      new SegmentMetadataEvent(
+          "ds2",
+          DateTimes.of("2020-01-01T00:00:00.000Z"),
+          DateTimes.of("2020-01-02T00:00:00.000Z"),
+          DateTimes.of("2020-01-03T00:00:00.000Z"),
+          "ds2",
+          true
+      )
+  );
+
+  private static final List<Event> UNKNOWN_EVENTS = ImmutableList.of(
+      new TestEvent(),
+      new TestEvent(),
+      new TestEvent()
+  );
+
+  @Test(timeout = 10_000)
+  public void testServiceMetricEvents() throws JsonProcessingException, InterruptedException
+  {
+    final KafkaEmitterConfig kafkaEmitterConfig = new KafkaEmitterConfig(
+        "",
+        new HashSet<>(Collections.singletonList(KafkaEmitterConfig.EventType.METRICS)),
+        "metrics",
+        "alerts",
+        "requests",
+        "segments",
+        "clusterName",
+        ImmutableMap.of("clusterId", "cluster-101"),
+        null,
+        null
+    );
+
+    final KafkaEmitter kafkaEmitter = initKafkaEmitter(kafkaEmitterConfig);
+
+    final List<Event> inputEvents = flattenEvents(SERVICE_METRIC_EVENTS);
+    final CountDownLatch eventLatch = new CountDownLatch(inputEvents.size());
+
+    final Map<String, List<String>> feedToExpectedEvents = trackExpectedEventsPerFeed(
+        inputEvents,
+        kafkaEmitterConfig.getClusterName(),
+        kafkaEmitterConfig.getExtraDimensions()
+    );
+    final Map<String, List<String>> feedToActualEvents = trackActualEventsPerFeed(eventLatch);
+
+    emitEvents(kafkaEmitter, inputEvents, eventLatch);
+
+    validateEvents(feedToExpectedEvents, feedToActualEvents);
+
+    Assert.assertEquals(0, kafkaEmitter.getMetricLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getAlertLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getSegmentMetadataLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getSegmentMetadataLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getInvalidLostCount());
+  }
+
+  @Test(timeout = 10_000)
+  public void testAllEvents() throws JsonProcessingException, InterruptedException
+  {
+    final KafkaEmitterConfig kafkaEmitterConfig = new KafkaEmitterConfig(
+        "",
+        new HashSet<>(Arrays.asList(KafkaEmitterConfig.EventType.values())),
+        "metrics",
+        "alerts",
+        "requests",
+        "segments",
+        null,
+        ImmutableMap.of("clusterId", "cluster-101", "env", "staging"),
+        null,
+        null
+    );
+
+    final KafkaEmitter kafkaEmitter = initKafkaEmitter(kafkaEmitterConfig);
+
+    final List<Event> inputEvents = flattenEvents(
+        SERVICE_METRIC_EVENTS,
+        ALERT_EVENTS,
+        REQUEST_LOG_EVENTS,
+        SEGMENT_METADATA_EVENTS
+    );
+    final CountDownLatch eventLatch = new CountDownLatch(inputEvents.size());
+
+    final Map<String, List<String>> feedToExpectedEvents = trackExpectedEventsPerFeed(
+        inputEvents,
+        kafkaEmitterConfig.getClusterName(),
+        kafkaEmitterConfig.getExtraDimensions()
+    );
+    final Map<String, List<String>> feedToActualEvents = trackActualEventsPerFeed(eventLatch);
+
+    emitEvents(kafkaEmitter, inputEvents, eventLatch);
+
+    validateEvents(feedToExpectedEvents, feedToActualEvents);
+
+    Assert.assertEquals(0, kafkaEmitter.getMetricLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getAlertLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getSegmentMetadataLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getSegmentMetadataLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getInvalidLostCount());
+
+  }
+
+  @Test(timeout = 10_000)
+  public void testDefaultEvents() throws JsonProcessingException, InterruptedException
+  {
+    final KafkaEmitterConfig kafkaEmitterConfig = new KafkaEmitterConfig(
+        "",
+        KafkaEmitterConfig.DEFAULT_EVENT_TYPES,
+        "metrics",
+        "alerts",
+        "requests",
+        "segment_metadata",
+        "clusterName",
+        null,
+        null,
+        null
+    );
+
+    final KafkaEmitter kafkaEmitter = initKafkaEmitter(kafkaEmitterConfig);
+
+    final List<Event> inputEvents = flattenEvents(
+        SERVICE_METRIC_EVENTS,
+        ALERT_EVENTS
+    );
+    final CountDownLatch eventLatch = new CountDownLatch(inputEvents.size());
+
+    final Map<String, List<String>> feedToExpectedEvents = trackExpectedEventsPerFeed(
+        inputEvents,
+        kafkaEmitterConfig.getClusterName(),
+        kafkaEmitterConfig.getExtraDimensions()
+    );
+    final Map<String, List<String>> feedToActualEvents = trackActualEventsPerFeed(eventLatch);
+
+    emitEvents(kafkaEmitter, inputEvents, eventLatch);
+
+    validateEvents(feedToExpectedEvents, feedToActualEvents);
+
+    Assert.assertEquals(0, kafkaEmitter.getMetricLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getAlertLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getSegmentMetadataLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getSegmentMetadataLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getInvalidLostCount());
+  }
+
+  @Test(timeout = 10_000)
+  public void testAlertsPlusUnsubscribedEvents() throws JsonProcessingException, InterruptedException
+  {
+    final KafkaEmitterConfig kafkaEmitterConfig = new KafkaEmitterConfig(
+        "",
+        new HashSet<>(Collections.singletonList(KafkaEmitterConfig.EventType.ALERTS)),
+        "metrics",
+        "alerts",
+        "requests",
+        "segment_metadata",
+        "clusterName",
+        null,
+        null,
+        null
+    );
+
+    final KafkaEmitter kafkaEmitter = initKafkaEmitter(kafkaEmitterConfig);
+
+    // Emit everything. Since we only subscribe to alert feeds, everything else should be dropped.
+    final List<Event> inputEvents = flattenEvents(
+        SERVICE_METRIC_EVENTS,
+        ALERT_EVENTS,
+        SEGMENT_METADATA_EVENTS,
+        REQUEST_LOG_EVENTS
+    );
+
+    final CountDownLatch eventLatch = new CountDownLatch(ALERT_EVENTS.size());
+
+    final Map<String, List<String>> feedToExpectedEvents = trackExpectedEventsPerFeed(
+        ALERT_EVENTS,
+        kafkaEmitterConfig.getClusterName(),
+        kafkaEmitterConfig.getExtraDimensions()
+    );
+    final Map<String, List<String>> feedToActualEvents = trackActualEventsPerFeed(eventLatch);
+
+    emitEvents(kafkaEmitter, inputEvents, eventLatch);
+
+    validateEvents(feedToExpectedEvents, feedToActualEvents);
+
+    Assert.assertEquals(0, kafkaEmitter.getAlertLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getInvalidLostCount());
+
+    // Others would be dropped as we've only subscribed to alert events.
+    Assert.assertEquals(SERVICE_METRIC_EVENTS.size(), kafkaEmitter.getMetricLostCount());
+    Assert.assertEquals(SEGMENT_METADATA_EVENTS.size(), kafkaEmitter.getSegmentMetadataLostCount());
+    Assert.assertEquals(REQUEST_LOG_EVENTS.size(), kafkaEmitter.getRequestLostCount());
+  }
+
+  @Test(timeout = 10_000)
+  public void testAllEventsWithCommonTopic() throws JsonProcessingException, InterruptedException
+  {
+    final KafkaEmitterConfig kafkaEmitterConfig = new KafkaEmitterConfig(
+        "",
+        new HashSet<>(Arrays.asList(KafkaEmitterConfig.EventType.values())),
+        "topic",
+        "topic",
+        "topic",
+        "topic",
+        null,
+        null,
+        null,
+        null
+    );
+
+    final KafkaEmitter kafkaEmitter = initKafkaEmitter(kafkaEmitterConfig);
+
+    final List<Event> inputEvents = flattenEvents(
+        SERVICE_METRIC_EVENTS,
+        ALERT_EVENTS,
+        SEGMENT_METADATA_EVENTS,
+        REQUEST_LOG_EVENTS
+    );
+
+    final CountDownLatch eventLatch = new CountDownLatch(inputEvents.size());
+
+    final Map<String, List<String>> feedToExpectedEvents = trackExpectedEventsPerFeed(
+        inputEvents,
+        kafkaEmitterConfig.getClusterName(),
+        kafkaEmitterConfig.getExtraDimensions()
+    );
+    final Map<String, List<String>> feedToActualEvents = trackActualEventsPerFeed(eventLatch);
+
+    emitEvents(kafkaEmitter, inputEvents, eventLatch);
+
+    validateEvents(feedToExpectedEvents, feedToActualEvents);
+
+    Assert.assertEquals(0, kafkaEmitter.getMetricLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getAlertLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getSegmentMetadataLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getSegmentMetadataLostCount());

Review Comment:
   ```suggestion
       Assert.assertEquals(0, kafkaEmitter.getRequestLostCount()());
   ```



##########
extensions-contrib/kafka-emitter/src/test/java/org/apache/druid/emitter/kafka/KafkaEmitterTest.java:
##########
@@ -19,95 +19,459 @@
 
 package org.apache.druid.emitter.kafka;
 
+import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.datatype.joda.JodaModule;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
+import org.apache.druid.jackson.DefaultObjectMapper;
 import org.apache.druid.java.util.common.DateTimes;
+import org.apache.druid.java.util.common.StringUtils;
 import org.apache.druid.java.util.emitter.core.Event;
+import org.apache.druid.java.util.emitter.core.EventMap;
 import org.apache.druid.java.util.emitter.service.AlertEvent;
 import org.apache.druid.java.util.emitter.service.SegmentMetadataEvent;
 import org.apache.druid.java.util.emitter.service.ServiceMetricEvent;
 import org.apache.druid.server.QueryStats;
 import org.apache.druid.server.RequestLogLine;
 import org.apache.druid.server.log.DefaultRequestLogEventBuilderFactory;
-import org.apache.druid.server.log.RequestLogEvent;
 import org.apache.kafka.clients.producer.KafkaProducer;
 import org.apache.kafka.clients.producer.Producer;
+import org.apache.kafka.clients.producer.ProducerConfig;
+import org.apache.kafka.clients.producer.ProducerRecord;
+import org.junit.After;
 import org.junit.Assert;
+import org.junit.Before;
 import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
 
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
-import java.util.Set;
+import java.util.Map;
 import java.util.concurrent.CountDownLatch;
 
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
-@RunWith(Parameterized.class)
 public class KafkaEmitterTest
 {
-  @Parameterized.Parameter(0)
-  public Set<KafkaEmitterConfig.EventType> eventsType;
+  private KafkaProducer<String, String> producer;
 
-  @Parameterized.Parameter(1)
-  public String requestTopic;
+  @Before
+  public void setup()
+  {
+    producer = mock(KafkaProducer.class);
+  }
 
-  @Parameterized.Parameters(name = "{index}: eventTypes - {0}, requestTopic - {1}")
-  public static Object[] data()
+  @After
+  public void tearDown()
   {
-    return new Object[][] {
-        {new HashSet<>(Arrays.asList(KafkaEmitterConfig.EventType.METRICS, KafkaEmitterConfig.EventType.REQUESTS, KafkaEmitterConfig.EventType.ALERTS, KafkaEmitterConfig.EventType.SEGMENT_METADATA)), "requests"},
-        {new HashSet<>(Arrays.asList(KafkaEmitterConfig.EventType.METRICS, KafkaEmitterConfig.EventType.ALERTS, KafkaEmitterConfig.EventType.SEGMENT_METADATA)), null}
-    };
+    producer.close();
+  }
+
+  private static final ObjectMapper MAPPER = new DefaultObjectMapper();
+
+  private static final List<Event> SERVICE_METRIC_EVENTS = ImmutableList.of(
+      ServiceMetricEvent.builder().setMetric("m1", 1).build("service1", "host1"),
+      ServiceMetricEvent.builder().setMetric("m2", 100).build("service2", "host1"),
+      ServiceMetricEvent.builder().setMetric("m3", 200).build("service2", "host1"),
+      ServiceMetricEvent.builder().setMetric("m1", 150).build("service2", "host2"),
+      ServiceMetricEvent.builder().setMetric("m5", 250).build("service3", "host2")
+  );
+
+  private static final List<Event> ALERT_EVENTS = ImmutableList.of(
+      new AlertEvent("service1", "host1", "description"),
+      new AlertEvent("service2", "host2", "description")
+  );
+
+  private static final List<Event> REQUEST_LOG_EVENTS = ImmutableList.of(
+      DefaultRequestLogEventBuilderFactory.instance().createRequestLogEventBuilder(
+          "requests",
+          RequestLogLine.forSql(
+              "sql1", null, DateTimes.nowUtc(), null, new QueryStats(ImmutableMap.of())
+          )
+      ).build("service", "host"),
+      DefaultRequestLogEventBuilderFactory.instance().createRequestLogEventBuilder(
+          "requests",
+          RequestLogLine.forSql(
+              "sql2", null, DateTimes.nowUtc(), null, new QueryStats(ImmutableMap.of())
+          )
+      ).build("service", "host")
+  );
+
+  private static final List<Event> SEGMENT_METADATA_EVENTS = ImmutableList.of(
+      new SegmentMetadataEvent(
+          "ds1",
+          DateTimes.of("2001-01-01T00:00:00.000Z"),
+          DateTimes.of("2001-01-02T00:00:00.000Z"),
+          DateTimes.of("2001-01-03T00:00:00.000Z"),
+          "ds1",
+          true
+      ),
+      new SegmentMetadataEvent(
+          "ds2",
+          DateTimes.of("2020-01-01T00:00:00.000Z"),
+          DateTimes.of("2020-01-02T00:00:00.000Z"),
+          DateTimes.of("2020-01-03T00:00:00.000Z"),
+          "ds2",
+          true
+      )
+  );
+
+  private static final List<Event> UNKNOWN_EVENTS = ImmutableList.of(
+      new TestEvent(),
+      new TestEvent(),
+      new TestEvent()
+  );
+
+  @Test(timeout = 10_000)
+  public void testServiceMetricEvents() throws JsonProcessingException, InterruptedException
+  {
+    final KafkaEmitterConfig kafkaEmitterConfig = new KafkaEmitterConfig(
+        "",
+        new HashSet<>(Collections.singletonList(KafkaEmitterConfig.EventType.METRICS)),
+        "metrics",
+        "alerts",
+        "requests",
+        "segments",
+        "clusterName",
+        ImmutableMap.of("clusterId", "cluster-101"),
+        null,
+        null
+    );
+
+    final KafkaEmitter kafkaEmitter = initKafkaEmitter(kafkaEmitterConfig);
+
+    final List<Event> inputEvents = flattenEvents(SERVICE_METRIC_EVENTS);
+    final CountDownLatch eventLatch = new CountDownLatch(inputEvents.size());
+
+    final Map<String, List<String>> feedToExpectedEvents = trackExpectedEventsPerFeed(
+        inputEvents,
+        kafkaEmitterConfig.getClusterName(),
+        kafkaEmitterConfig.getExtraDimensions()
+    );
+    final Map<String, List<String>> feedToActualEvents = trackActualEventsPerFeed(eventLatch);
+
+    emitEvents(kafkaEmitter, inputEvents, eventLatch);
+
+    validateEvents(feedToExpectedEvents, feedToActualEvents);
+
+    Assert.assertEquals(0, kafkaEmitter.getMetricLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getAlertLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getSegmentMetadataLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getSegmentMetadataLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getInvalidLostCount());
+  }
+
+  @Test(timeout = 10_000)
+  public void testAllEvents() throws JsonProcessingException, InterruptedException
+  {
+    final KafkaEmitterConfig kafkaEmitterConfig = new KafkaEmitterConfig(
+        "",
+        new HashSet<>(Arrays.asList(KafkaEmitterConfig.EventType.values())),
+        "metrics",
+        "alerts",
+        "requests",
+        "segments",
+        null,
+        ImmutableMap.of("clusterId", "cluster-101", "env", "staging"),
+        null,
+        null
+    );
+
+    final KafkaEmitter kafkaEmitter = initKafkaEmitter(kafkaEmitterConfig);
+
+    final List<Event> inputEvents = flattenEvents(
+        SERVICE_METRIC_EVENTS,
+        ALERT_EVENTS,
+        REQUEST_LOG_EVENTS,
+        SEGMENT_METADATA_EVENTS
+    );
+    final CountDownLatch eventLatch = new CountDownLatch(inputEvents.size());
+
+    final Map<String, List<String>> feedToExpectedEvents = trackExpectedEventsPerFeed(
+        inputEvents,
+        kafkaEmitterConfig.getClusterName(),
+        kafkaEmitterConfig.getExtraDimensions()
+    );
+    final Map<String, List<String>> feedToActualEvents = trackActualEventsPerFeed(eventLatch);
+
+    emitEvents(kafkaEmitter, inputEvents, eventLatch);
+
+    validateEvents(feedToExpectedEvents, feedToActualEvents);
+
+    Assert.assertEquals(0, kafkaEmitter.getMetricLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getAlertLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getSegmentMetadataLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getSegmentMetadataLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getInvalidLostCount());
+
+  }
+
+  @Test(timeout = 10_000)
+  public void testDefaultEvents() throws JsonProcessingException, InterruptedException
+  {
+    final KafkaEmitterConfig kafkaEmitterConfig = new KafkaEmitterConfig(
+        "",
+        KafkaEmitterConfig.DEFAULT_EVENT_TYPES,
+        "metrics",
+        "alerts",
+        "requests",
+        "segment_metadata",
+        "clusterName",
+        null,
+        null,
+        null
+    );
+
+    final KafkaEmitter kafkaEmitter = initKafkaEmitter(kafkaEmitterConfig);
+
+    final List<Event> inputEvents = flattenEvents(
+        SERVICE_METRIC_EVENTS,
+        ALERT_EVENTS
+    );
+    final CountDownLatch eventLatch = new CountDownLatch(inputEvents.size());
+
+    final Map<String, List<String>> feedToExpectedEvents = trackExpectedEventsPerFeed(
+        inputEvents,
+        kafkaEmitterConfig.getClusterName(),
+        kafkaEmitterConfig.getExtraDimensions()
+    );
+    final Map<String, List<String>> feedToActualEvents = trackActualEventsPerFeed(eventLatch);
+
+    emitEvents(kafkaEmitter, inputEvents, eventLatch);
+
+    validateEvents(feedToExpectedEvents, feedToActualEvents);
+
+    Assert.assertEquals(0, kafkaEmitter.getMetricLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getAlertLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getSegmentMetadataLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getSegmentMetadataLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getInvalidLostCount());
+  }
+
+  @Test(timeout = 10_000)
+  public void testAlertsPlusUnsubscribedEvents() throws JsonProcessingException, InterruptedException
+  {
+    final KafkaEmitterConfig kafkaEmitterConfig = new KafkaEmitterConfig(
+        "",
+        new HashSet<>(Collections.singletonList(KafkaEmitterConfig.EventType.ALERTS)),
+        "metrics",
+        "alerts",
+        "requests",
+        "segment_metadata",
+        "clusterName",
+        null,
+        null,
+        null
+    );
+
+    final KafkaEmitter kafkaEmitter = initKafkaEmitter(kafkaEmitterConfig);
+
+    // Emit everything. Since we only subscribe to alert feeds, everything else should be dropped.
+    final List<Event> inputEvents = flattenEvents(
+        SERVICE_METRIC_EVENTS,
+        ALERT_EVENTS,
+        SEGMENT_METADATA_EVENTS,
+        REQUEST_LOG_EVENTS
+    );
+
+    final CountDownLatch eventLatch = new CountDownLatch(ALERT_EVENTS.size());
+
+    final Map<String, List<String>> feedToExpectedEvents = trackExpectedEventsPerFeed(
+        ALERT_EVENTS,
+        kafkaEmitterConfig.getClusterName(),
+        kafkaEmitterConfig.getExtraDimensions()
+    );
+    final Map<String, List<String>> feedToActualEvents = trackActualEventsPerFeed(eventLatch);
+
+    emitEvents(kafkaEmitter, inputEvents, eventLatch);
+
+    validateEvents(feedToExpectedEvents, feedToActualEvents);
+
+    Assert.assertEquals(0, kafkaEmitter.getAlertLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getInvalidLostCount());
+
+    // Others would be dropped as we've only subscribed to alert events.
+    Assert.assertEquals(SERVICE_METRIC_EVENTS.size(), kafkaEmitter.getMetricLostCount());
+    Assert.assertEquals(SEGMENT_METADATA_EVENTS.size(), kafkaEmitter.getSegmentMetadataLostCount());
+    Assert.assertEquals(REQUEST_LOG_EVENTS.size(), kafkaEmitter.getRequestLostCount());
+  }
+
+  @Test(timeout = 10_000)
+  public void testAllEventsWithCommonTopic() throws JsonProcessingException, InterruptedException
+  {
+    final KafkaEmitterConfig kafkaEmitterConfig = new KafkaEmitterConfig(
+        "",
+        new HashSet<>(Arrays.asList(KafkaEmitterConfig.EventType.values())),
+        "topic",
+        "topic",
+        "topic",
+        "topic",
+        null,
+        null,
+        null,
+        null
+    );
+
+    final KafkaEmitter kafkaEmitter = initKafkaEmitter(kafkaEmitterConfig);
+
+    final List<Event> inputEvents = flattenEvents(
+        SERVICE_METRIC_EVENTS,
+        ALERT_EVENTS,
+        SEGMENT_METADATA_EVENTS,
+        REQUEST_LOG_EVENTS
+    );
+
+    final CountDownLatch eventLatch = new CountDownLatch(inputEvents.size());
+
+    final Map<String, List<String>> feedToExpectedEvents = trackExpectedEventsPerFeed(
+        inputEvents,
+        kafkaEmitterConfig.getClusterName(),
+        kafkaEmitterConfig.getExtraDimensions()
+    );
+    final Map<String, List<String>> feedToActualEvents = trackActualEventsPerFeed(eventLatch);
+
+    emitEvents(kafkaEmitter, inputEvents, eventLatch);
+
+    validateEvents(feedToExpectedEvents, feedToActualEvents);
+
+    Assert.assertEquals(0, kafkaEmitter.getMetricLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getAlertLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getSegmentMetadataLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getSegmentMetadataLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getInvalidLostCount());
+  }
+
+  @Test(timeout = 10_000)
+  public void testUnknownEvents() throws JsonProcessingException, InterruptedException
+  {
+    final KafkaEmitterConfig kafkaEmitterConfig = new KafkaEmitterConfig(
+        "",
+        KafkaEmitterConfig.DEFAULT_EVENT_TYPES,
+        "topic",
+        "topic",
+        null,
+        null,
+        "cluster-102",
+        ImmutableMap.of("clusterName", "cluster-101", "env", "staging"), // clusterName again, extraDimensions should take precedence
+        null,
+        null
+    );
+
+    final KafkaEmitter kafkaEmitter = initKafkaEmitter(kafkaEmitterConfig);
+
+    final List<Event> inputEvents = flattenEvents(
+        UNKNOWN_EVENTS,
+        SERVICE_METRIC_EVENTS
+    );
+
+    final CountDownLatch eventLatch = new CountDownLatch(SERVICE_METRIC_EVENTS.size());
+
+    final Map<String, List<String>> feedToExpectedEvents = trackExpectedEventsPerFeed(
+        SERVICE_METRIC_EVENTS,
+        kafkaEmitterConfig.getClusterName(),
+        kafkaEmitterConfig.getExtraDimensions()
+    );
+    final Map<String, List<String>> feedToActualEvents = trackActualEventsPerFeed(eventLatch);
+
+    emitEvents(kafkaEmitter, inputEvents, eventLatch);
+
+    validateEvents(feedToExpectedEvents, feedToActualEvents);
+
+    Assert.assertEquals(0, kafkaEmitter.getMetricLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getAlertLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getSegmentMetadataLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getSegmentMetadataLostCount());

Review Comment:
   ```suggestion
       Assert.assertEquals(0, kafkaEmitter.getRequestLostCount()());
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] Clean up kafka emitter tests, add more validations and code coverage. (druid)

Posted by "zachjsh (via GitHub)" <gi...@apache.org>.
zachjsh commented on code in PR #15878:
URL: https://github.com/apache/druid/pull/15878#discussion_r1486448343


##########
extensions-contrib/kafka-emitter/src/main/java/org/apache/druid/emitter/kafka/KafkaEmitterConfig.java:
##########
@@ -95,12 +95,45 @@ public KafkaEmitterConfig(
       @JsonProperty("producer.hiddenProperties") @Nullable DynamicConfigProvider<String> kafkaProducerSecrets
   )
   {
-    this.bootstrapServers = Preconditions.checkNotNull(bootstrapServers, "druid.emitter.kafka.bootstrap.servers can not be null");
     this.eventTypes = maybeUpdateEventTypes(eventTypes, requestTopic);
-    this.metricTopic = this.eventTypes.contains(EventType.METRICS) ? Preconditions.checkNotNull(metricTopic, "druid.emitter.kafka.metric.topic can not be null") : null;
-    this.alertTopic = this.eventTypes.contains(EventType.ALERTS) ? Preconditions.checkNotNull(alertTopic, "druid.emitter.kafka.alert.topic can not be null") : null;
-    this.requestTopic = this.eventTypes.contains(EventType.REQUESTS) ? Preconditions.checkNotNull(requestTopic, "druid.emitter.kafka.request.topic can not be null") : null;
-    this.segmentMetadataTopic = this.eventTypes.contains(EventType.SEGMENT_METADATA) ? Preconditions.checkNotNull(segmentMetadataTopic, "druid.emitter.kafka.segmentMetadata.topic can not be null") : null;
+
+    // Validate all required properties
+    if (bootstrapServers == null) {
+      throw DruidException.forPersona(DruidException.Persona.OPERATOR)
+                          .ofCategory(DruidException.Category.NOT_FOUND)
+                          .build("druid.emitter.kafka.bootstrap.servers must be specified.");
+    }
+
+    if (this.eventTypes.contains(EventType.METRICS) && metricTopic == null) {
+      throw DruidException.forPersona(DruidException.Persona.OPERATOR)
+                          .ofCategory(DruidException.Category.NOT_FOUND)
+                          .build("druid.emitter.kafka.metric.topic must be specified"
+                                 + " if druid.emitter.kafka.event.types contains %s.", EventType.METRICS);
+    }
+    if (this.eventTypes.contains(EventType.ALERTS) && alertTopic == null) {

Review Comment:
   Should we combine the 3 blocks below, and includ all three of these properties in the `if druid.emitter.kafka.event.types contains %s.` part of error message? If we want to keep it separate like this, should we put that message in a static error string variable? Seems the same for each, just the type is different, which could be added using string formatter.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] Clean up kafka emitter tests, add more validations and code coverage. (druid)

Posted by "zachjsh (via GitHub)" <gi...@apache.org>.
zachjsh commented on code in PR #15878:
URL: https://github.com/apache/druid/pull/15878#discussion_r1486449588


##########
extensions-contrib/kafka-emitter/src/main/java/org/apache/druid/emitter/kafka/KafkaEmitterConfig.java:
##########
@@ -95,12 +95,45 @@ public KafkaEmitterConfig(
       @JsonProperty("producer.hiddenProperties") @Nullable DynamicConfigProvider<String> kafkaProducerSecrets
   )
   {
-    this.bootstrapServers = Preconditions.checkNotNull(bootstrapServers, "druid.emitter.kafka.bootstrap.servers can not be null");
     this.eventTypes = maybeUpdateEventTypes(eventTypes, requestTopic);
-    this.metricTopic = this.eventTypes.contains(EventType.METRICS) ? Preconditions.checkNotNull(metricTopic, "druid.emitter.kafka.metric.topic can not be null") : null;
-    this.alertTopic = this.eventTypes.contains(EventType.ALERTS) ? Preconditions.checkNotNull(alertTopic, "druid.emitter.kafka.alert.topic can not be null") : null;
-    this.requestTopic = this.eventTypes.contains(EventType.REQUESTS) ? Preconditions.checkNotNull(requestTopic, "druid.emitter.kafka.request.topic can not be null") : null;
-    this.segmentMetadataTopic = this.eventTypes.contains(EventType.SEGMENT_METADATA) ? Preconditions.checkNotNull(segmentMetadataTopic, "druid.emitter.kafka.segmentMetadata.topic can not be null") : null;
+
+    // Validate all required properties
+    if (bootstrapServers == null) {
+      throw DruidException.forPersona(DruidException.Persona.OPERATOR)
+                          .ofCategory(DruidException.Category.NOT_FOUND)
+                          .build("druid.emitter.kafka.bootstrap.servers must be specified.");
+    }
+
+    if (this.eventTypes.contains(EventType.METRICS) && metricTopic == null) {

Review Comment:
   Should we combine the 4 blocks below, and includ all three of these properties in the if druid.emitter.kafka.event.types contains %s. part of error message? If we want to keep it separate like this, should we put that message in a static error string variable? Seems the same for each, just the type is different, which could be added using string formatter.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] Clean up kafka emitter tests, add more validations and code coverage. (druid)

Posted by "zachjsh (via GitHub)" <gi...@apache.org>.
zachjsh commented on code in PR #15878:
URL: https://github.com/apache/druid/pull/15878#discussion_r1486448343


##########
extensions-contrib/kafka-emitter/src/main/java/org/apache/druid/emitter/kafka/KafkaEmitterConfig.java:
##########
@@ -95,12 +95,45 @@ public KafkaEmitterConfig(
       @JsonProperty("producer.hiddenProperties") @Nullable DynamicConfigProvider<String> kafkaProducerSecrets
   )
   {
-    this.bootstrapServers = Preconditions.checkNotNull(bootstrapServers, "druid.emitter.kafka.bootstrap.servers can not be null");
     this.eventTypes = maybeUpdateEventTypes(eventTypes, requestTopic);
-    this.metricTopic = this.eventTypes.contains(EventType.METRICS) ? Preconditions.checkNotNull(metricTopic, "druid.emitter.kafka.metric.topic can not be null") : null;
-    this.alertTopic = this.eventTypes.contains(EventType.ALERTS) ? Preconditions.checkNotNull(alertTopic, "druid.emitter.kafka.alert.topic can not be null") : null;
-    this.requestTopic = this.eventTypes.contains(EventType.REQUESTS) ? Preconditions.checkNotNull(requestTopic, "druid.emitter.kafka.request.topic can not be null") : null;
-    this.segmentMetadataTopic = this.eventTypes.contains(EventType.SEGMENT_METADATA) ? Preconditions.checkNotNull(segmentMetadataTopic, "druid.emitter.kafka.segmentMetadata.topic can not be null") : null;
+
+    // Validate all required properties
+    if (bootstrapServers == null) {
+      throw DruidException.forPersona(DruidException.Persona.OPERATOR)
+                          .ofCategory(DruidException.Category.NOT_FOUND)
+                          .build("druid.emitter.kafka.bootstrap.servers must be specified.");
+    }
+
+    if (this.eventTypes.contains(EventType.METRICS) && metricTopic == null) {
+      throw DruidException.forPersona(DruidException.Persona.OPERATOR)
+                          .ofCategory(DruidException.Category.NOT_FOUND)
+                          .build("druid.emitter.kafka.metric.topic must be specified"
+                                 + " if druid.emitter.kafka.event.types contains %s.", EventType.METRICS);
+    }
+    if (this.eventTypes.contains(EventType.ALERTS) && alertTopic == null) {

Review Comment:
   Should we combine the 3 blocks below, and includ all three of these properties in the `if druid.emitter.kafka.event.types contains %s.` part of error message? If we want to keep it separate like this, should we put that message in a static error string variable? Seems the same for each, just the type is different, which could be added using string formatter.



##########
extensions-contrib/kafka-emitter/src/main/java/org/apache/druid/emitter/kafka/KafkaEmitterConfig.java:
##########
@@ -95,12 +95,45 @@ public KafkaEmitterConfig(
       @JsonProperty("producer.hiddenProperties") @Nullable DynamicConfigProvider<String> kafkaProducerSecrets
   )
   {
-    this.bootstrapServers = Preconditions.checkNotNull(bootstrapServers, "druid.emitter.kafka.bootstrap.servers can not be null");
     this.eventTypes = maybeUpdateEventTypes(eventTypes, requestTopic);
-    this.metricTopic = this.eventTypes.contains(EventType.METRICS) ? Preconditions.checkNotNull(metricTopic, "druid.emitter.kafka.metric.topic can not be null") : null;
-    this.alertTopic = this.eventTypes.contains(EventType.ALERTS) ? Preconditions.checkNotNull(alertTopic, "druid.emitter.kafka.alert.topic can not be null") : null;
-    this.requestTopic = this.eventTypes.contains(EventType.REQUESTS) ? Preconditions.checkNotNull(requestTopic, "druid.emitter.kafka.request.topic can not be null") : null;
-    this.segmentMetadataTopic = this.eventTypes.contains(EventType.SEGMENT_METADATA) ? Preconditions.checkNotNull(segmentMetadataTopic, "druid.emitter.kafka.segmentMetadata.topic can not be null") : null;
+
+    // Validate all required properties
+    if (bootstrapServers == null) {
+      throw DruidException.forPersona(DruidException.Persona.OPERATOR)
+                          .ofCategory(DruidException.Category.NOT_FOUND)
+                          .build("druid.emitter.kafka.bootstrap.servers must be specified.");
+    }
+
+    if (this.eventTypes.contains(EventType.METRICS) && metricTopic == null) {

Review Comment:
   Should we combine the 4 blocks below, and includ all three of these properties in the if druid.emitter.kafka.event.types contains %s. part of error message? If we want to keep it separate like this, should we put that message in a static error string variable? Seems the same for each, just the type is different, which could be added using string formatter.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] Clean up kafka emitter tests, add more validations and code coverage. (druid)

Posted by "TSFenwick (via GitHub)" <gi...@apache.org>.
TSFenwick commented on code in PR #15878:
URL: https://github.com/apache/druid/pull/15878#discussion_r1486553480


##########
extensions-contrib/kafka-emitter/src/test/java/org/apache/druid/emitter/kafka/KafkaEmitterTest.java:
##########
@@ -19,95 +19,459 @@
 
 package org.apache.druid.emitter.kafka;
 
+import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.datatype.joda.JodaModule;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
+import org.apache.druid.jackson.DefaultObjectMapper;
 import org.apache.druid.java.util.common.DateTimes;
+import org.apache.druid.java.util.common.StringUtils;
 import org.apache.druid.java.util.emitter.core.Event;
+import org.apache.druid.java.util.emitter.core.EventMap;
 import org.apache.druid.java.util.emitter.service.AlertEvent;
 import org.apache.druid.java.util.emitter.service.SegmentMetadataEvent;
 import org.apache.druid.java.util.emitter.service.ServiceMetricEvent;
 import org.apache.druid.server.QueryStats;
 import org.apache.druid.server.RequestLogLine;
 import org.apache.druid.server.log.DefaultRequestLogEventBuilderFactory;
-import org.apache.druid.server.log.RequestLogEvent;
 import org.apache.kafka.clients.producer.KafkaProducer;
 import org.apache.kafka.clients.producer.Producer;
+import org.apache.kafka.clients.producer.ProducerConfig;
+import org.apache.kafka.clients.producer.ProducerRecord;
+import org.junit.After;
 import org.junit.Assert;
+import org.junit.Before;
 import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
 
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
-import java.util.Set;
+import java.util.Map;
 import java.util.concurrent.CountDownLatch;
 
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
-@RunWith(Parameterized.class)
 public class KafkaEmitterTest
 {
-  @Parameterized.Parameter(0)
-  public Set<KafkaEmitterConfig.EventType> eventsType;
+  private KafkaProducer<String, String> producer;
 
-  @Parameterized.Parameter(1)
-  public String requestTopic;
+  @Before
+  public void setup()
+  {
+    producer = mock(KafkaProducer.class);
+  }
 
-  @Parameterized.Parameters(name = "{index}: eventTypes - {0}, requestTopic - {1}")
-  public static Object[] data()
+  @After
+  public void tearDown()
   {
-    return new Object[][] {
-        {new HashSet<>(Arrays.asList(KafkaEmitterConfig.EventType.METRICS, KafkaEmitterConfig.EventType.REQUESTS, KafkaEmitterConfig.EventType.ALERTS, KafkaEmitterConfig.EventType.SEGMENT_METADATA)), "requests"},
-        {new HashSet<>(Arrays.asList(KafkaEmitterConfig.EventType.METRICS, KafkaEmitterConfig.EventType.ALERTS, KafkaEmitterConfig.EventType.SEGMENT_METADATA)), null}
-    };
+    producer.close();
+  }
+
+  private static final ObjectMapper MAPPER = new DefaultObjectMapper();
+
+  private static final List<Event> SERVICE_METRIC_EVENTS = ImmutableList.of(
+      ServiceMetricEvent.builder().setMetric("m1", 1).build("service1", "host1"),
+      ServiceMetricEvent.builder().setMetric("m2", 100).build("service2", "host1"),
+      ServiceMetricEvent.builder().setMetric("m3", 200).build("service2", "host1"),
+      ServiceMetricEvent.builder().setMetric("m1", 150).build("service2", "host2"),
+      ServiceMetricEvent.builder().setMetric("m5", 250).build("service3", "host2")
+  );
+
+  private static final List<Event> ALERT_EVENTS = ImmutableList.of(
+      new AlertEvent("service1", "host1", "description"),
+      new AlertEvent("service2", "host2", "description")
+  );
+
+  private static final List<Event> REQUEST_LOG_EVENTS = ImmutableList.of(
+      DefaultRequestLogEventBuilderFactory.instance().createRequestLogEventBuilder(
+          "requests",
+          RequestLogLine.forSql(
+              "sql1", null, DateTimes.nowUtc(), null, new QueryStats(ImmutableMap.of())
+          )
+      ).build("service", "host"),
+      DefaultRequestLogEventBuilderFactory.instance().createRequestLogEventBuilder(
+          "requests",
+          RequestLogLine.forSql(
+              "sql2", null, DateTimes.nowUtc(), null, new QueryStats(ImmutableMap.of())
+          )
+      ).build("service", "host")
+  );
+
+  private static final List<Event> SEGMENT_METADATA_EVENTS = ImmutableList.of(
+      new SegmentMetadataEvent(
+          "ds1",
+          DateTimes.of("2001-01-01T00:00:00.000Z"),
+          DateTimes.of("2001-01-02T00:00:00.000Z"),
+          DateTimes.of("2001-01-03T00:00:00.000Z"),
+          "ds1",
+          true
+      ),
+      new SegmentMetadataEvent(
+          "ds2",
+          DateTimes.of("2020-01-01T00:00:00.000Z"),
+          DateTimes.of("2020-01-02T00:00:00.000Z"),
+          DateTimes.of("2020-01-03T00:00:00.000Z"),
+          "ds2",
+          true
+      )
+  );
+
+  private static final List<Event> UNKNOWN_EVENTS = ImmutableList.of(
+      new TestEvent(),
+      new TestEvent(),
+      new TestEvent()
+  );
+
+  @Test(timeout = 10_000)
+  public void testServiceMetricEvents() throws JsonProcessingException, InterruptedException
+  {
+    final KafkaEmitterConfig kafkaEmitterConfig = new KafkaEmitterConfig(
+        "",
+        new HashSet<>(Collections.singletonList(KafkaEmitterConfig.EventType.METRICS)),
+        "metrics",
+        "alerts",
+        "requests",
+        "segments",
+        "clusterName",
+        ImmutableMap.of("clusterId", "cluster-101"),
+        null,
+        null
+    );
+
+    final KafkaEmitter kafkaEmitter = initKafkaEmitter(kafkaEmitterConfig);
+
+    final List<Event> inputEvents = flattenEvents(SERVICE_METRIC_EVENTS);
+    final CountDownLatch eventLatch = new CountDownLatch(inputEvents.size());
+
+    final Map<String, List<String>> feedToExpectedEvents = trackExpectedEventsPerFeed(
+        inputEvents,
+        kafkaEmitterConfig.getClusterName(),
+        kafkaEmitterConfig.getExtraDimensions()
+    );
+    final Map<String, List<String>> feedToActualEvents = trackActualEventsPerFeed(eventLatch);
+
+    emitEvents(kafkaEmitter, inputEvents, eventLatch);
+
+    validateEvents(feedToExpectedEvents, feedToActualEvents);
+
+    Assert.assertEquals(0, kafkaEmitter.getMetricLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getAlertLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getSegmentMetadataLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getSegmentMetadataLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getInvalidLostCount());
+  }
+
+  @Test(timeout = 10_000)
+  public void testAllEvents() throws JsonProcessingException, InterruptedException
+  {
+    final KafkaEmitterConfig kafkaEmitterConfig = new KafkaEmitterConfig(
+        "",
+        new HashSet<>(Arrays.asList(KafkaEmitterConfig.EventType.values())),
+        "metrics",
+        "alerts",
+        "requests",
+        "segments",
+        null,
+        ImmutableMap.of("clusterId", "cluster-101", "env", "staging"),
+        null,
+        null
+    );
+
+    final KafkaEmitter kafkaEmitter = initKafkaEmitter(kafkaEmitterConfig);
+
+    final List<Event> inputEvents = flattenEvents(
+        SERVICE_METRIC_EVENTS,
+        ALERT_EVENTS,
+        REQUEST_LOG_EVENTS,
+        SEGMENT_METADATA_EVENTS
+    );
+    final CountDownLatch eventLatch = new CountDownLatch(inputEvents.size());
+
+    final Map<String, List<String>> feedToExpectedEvents = trackExpectedEventsPerFeed(
+        inputEvents,
+        kafkaEmitterConfig.getClusterName(),
+        kafkaEmitterConfig.getExtraDimensions()
+    );
+    final Map<String, List<String>> feedToActualEvents = trackActualEventsPerFeed(eventLatch);
+
+    emitEvents(kafkaEmitter, inputEvents, eventLatch);
+
+    validateEvents(feedToExpectedEvents, feedToActualEvents);
+
+    Assert.assertEquals(0, kafkaEmitter.getMetricLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getAlertLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getSegmentMetadataLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getSegmentMetadataLostCount());

Review Comment:
   ```suggestion
       Assert.assertEquals(0, kafkaEmitter.getRequestLostCount()());
   ```



##########
extensions-contrib/kafka-emitter/src/test/java/org/apache/druid/emitter/kafka/KafkaEmitterTest.java:
##########
@@ -19,95 +19,459 @@
 
 package org.apache.druid.emitter.kafka;
 
+import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.datatype.joda.JodaModule;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
+import org.apache.druid.jackson.DefaultObjectMapper;
 import org.apache.druid.java.util.common.DateTimes;
+import org.apache.druid.java.util.common.StringUtils;
 import org.apache.druid.java.util.emitter.core.Event;
+import org.apache.druid.java.util.emitter.core.EventMap;
 import org.apache.druid.java.util.emitter.service.AlertEvent;
 import org.apache.druid.java.util.emitter.service.SegmentMetadataEvent;
 import org.apache.druid.java.util.emitter.service.ServiceMetricEvent;
 import org.apache.druid.server.QueryStats;
 import org.apache.druid.server.RequestLogLine;
 import org.apache.druid.server.log.DefaultRequestLogEventBuilderFactory;
-import org.apache.druid.server.log.RequestLogEvent;
 import org.apache.kafka.clients.producer.KafkaProducer;
 import org.apache.kafka.clients.producer.Producer;
+import org.apache.kafka.clients.producer.ProducerConfig;
+import org.apache.kafka.clients.producer.ProducerRecord;
+import org.junit.After;
 import org.junit.Assert;
+import org.junit.Before;
 import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
 
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
-import java.util.Set;
+import java.util.Map;
 import java.util.concurrent.CountDownLatch;
 
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
-@RunWith(Parameterized.class)
 public class KafkaEmitterTest
 {
-  @Parameterized.Parameter(0)
-  public Set<KafkaEmitterConfig.EventType> eventsType;
+  private KafkaProducer<String, String> producer;
 
-  @Parameterized.Parameter(1)
-  public String requestTopic;
+  @Before
+  public void setup()
+  {
+    producer = mock(KafkaProducer.class);
+  }
 
-  @Parameterized.Parameters(name = "{index}: eventTypes - {0}, requestTopic - {1}")
-  public static Object[] data()
+  @After
+  public void tearDown()
   {
-    return new Object[][] {
-        {new HashSet<>(Arrays.asList(KafkaEmitterConfig.EventType.METRICS, KafkaEmitterConfig.EventType.REQUESTS, KafkaEmitterConfig.EventType.ALERTS, KafkaEmitterConfig.EventType.SEGMENT_METADATA)), "requests"},
-        {new HashSet<>(Arrays.asList(KafkaEmitterConfig.EventType.METRICS, KafkaEmitterConfig.EventType.ALERTS, KafkaEmitterConfig.EventType.SEGMENT_METADATA)), null}
-    };
+    producer.close();
+  }
+
+  private static final ObjectMapper MAPPER = new DefaultObjectMapper();
+
+  private static final List<Event> SERVICE_METRIC_EVENTS = ImmutableList.of(
+      ServiceMetricEvent.builder().setMetric("m1", 1).build("service1", "host1"),
+      ServiceMetricEvent.builder().setMetric("m2", 100).build("service2", "host1"),
+      ServiceMetricEvent.builder().setMetric("m3", 200).build("service2", "host1"),
+      ServiceMetricEvent.builder().setMetric("m1", 150).build("service2", "host2"),
+      ServiceMetricEvent.builder().setMetric("m5", 250).build("service3", "host2")
+  );
+
+  private static final List<Event> ALERT_EVENTS = ImmutableList.of(
+      new AlertEvent("service1", "host1", "description"),
+      new AlertEvent("service2", "host2", "description")
+  );
+
+  private static final List<Event> REQUEST_LOG_EVENTS = ImmutableList.of(
+      DefaultRequestLogEventBuilderFactory.instance().createRequestLogEventBuilder(
+          "requests",
+          RequestLogLine.forSql(
+              "sql1", null, DateTimes.nowUtc(), null, new QueryStats(ImmutableMap.of())
+          )
+      ).build("service", "host"),
+      DefaultRequestLogEventBuilderFactory.instance().createRequestLogEventBuilder(
+          "requests",
+          RequestLogLine.forSql(
+              "sql2", null, DateTimes.nowUtc(), null, new QueryStats(ImmutableMap.of())
+          )
+      ).build("service", "host")
+  );
+
+  private static final List<Event> SEGMENT_METADATA_EVENTS = ImmutableList.of(
+      new SegmentMetadataEvent(
+          "ds1",
+          DateTimes.of("2001-01-01T00:00:00.000Z"),
+          DateTimes.of("2001-01-02T00:00:00.000Z"),
+          DateTimes.of("2001-01-03T00:00:00.000Z"),
+          "ds1",
+          true
+      ),
+      new SegmentMetadataEvent(
+          "ds2",
+          DateTimes.of("2020-01-01T00:00:00.000Z"),
+          DateTimes.of("2020-01-02T00:00:00.000Z"),
+          DateTimes.of("2020-01-03T00:00:00.000Z"),
+          "ds2",
+          true
+      )
+  );
+
+  private static final List<Event> UNKNOWN_EVENTS = ImmutableList.of(
+      new TestEvent(),
+      new TestEvent(),
+      new TestEvent()
+  );
+
+  @Test(timeout = 10_000)
+  public void testServiceMetricEvents() throws JsonProcessingException, InterruptedException
+  {
+    final KafkaEmitterConfig kafkaEmitterConfig = new KafkaEmitterConfig(
+        "",
+        new HashSet<>(Collections.singletonList(KafkaEmitterConfig.EventType.METRICS)),
+        "metrics",
+        "alerts",
+        "requests",
+        "segments",
+        "clusterName",
+        ImmutableMap.of("clusterId", "cluster-101"),
+        null,
+        null
+    );
+
+    final KafkaEmitter kafkaEmitter = initKafkaEmitter(kafkaEmitterConfig);
+
+    final List<Event> inputEvents = flattenEvents(SERVICE_METRIC_EVENTS);
+    final CountDownLatch eventLatch = new CountDownLatch(inputEvents.size());
+
+    final Map<String, List<String>> feedToExpectedEvents = trackExpectedEventsPerFeed(
+        inputEvents,
+        kafkaEmitterConfig.getClusterName(),
+        kafkaEmitterConfig.getExtraDimensions()
+    );
+    final Map<String, List<String>> feedToActualEvents = trackActualEventsPerFeed(eventLatch);
+
+    emitEvents(kafkaEmitter, inputEvents, eventLatch);
+
+    validateEvents(feedToExpectedEvents, feedToActualEvents);
+
+    Assert.assertEquals(0, kafkaEmitter.getMetricLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getAlertLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getSegmentMetadataLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getSegmentMetadataLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getInvalidLostCount());
+  }
+
+  @Test(timeout = 10_000)
+  public void testAllEvents() throws JsonProcessingException, InterruptedException
+  {
+    final KafkaEmitterConfig kafkaEmitterConfig = new KafkaEmitterConfig(
+        "",
+        new HashSet<>(Arrays.asList(KafkaEmitterConfig.EventType.values())),
+        "metrics",
+        "alerts",
+        "requests",
+        "segments",
+        null,
+        ImmutableMap.of("clusterId", "cluster-101", "env", "staging"),
+        null,
+        null
+    );
+
+    final KafkaEmitter kafkaEmitter = initKafkaEmitter(kafkaEmitterConfig);
+
+    final List<Event> inputEvents = flattenEvents(
+        SERVICE_METRIC_EVENTS,
+        ALERT_EVENTS,
+        REQUEST_LOG_EVENTS,
+        SEGMENT_METADATA_EVENTS
+    );
+    final CountDownLatch eventLatch = new CountDownLatch(inputEvents.size());
+
+    final Map<String, List<String>> feedToExpectedEvents = trackExpectedEventsPerFeed(
+        inputEvents,
+        kafkaEmitterConfig.getClusterName(),
+        kafkaEmitterConfig.getExtraDimensions()
+    );
+    final Map<String, List<String>> feedToActualEvents = trackActualEventsPerFeed(eventLatch);
+
+    emitEvents(kafkaEmitter, inputEvents, eventLatch);
+
+    validateEvents(feedToExpectedEvents, feedToActualEvents);
+
+    Assert.assertEquals(0, kafkaEmitter.getMetricLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getAlertLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getSegmentMetadataLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getSegmentMetadataLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getInvalidLostCount());
+
+  }
+
+  @Test(timeout = 10_000)
+  public void testDefaultEvents() throws JsonProcessingException, InterruptedException
+  {
+    final KafkaEmitterConfig kafkaEmitterConfig = new KafkaEmitterConfig(
+        "",
+        KafkaEmitterConfig.DEFAULT_EVENT_TYPES,
+        "metrics",
+        "alerts",
+        "requests",
+        "segment_metadata",
+        "clusterName",
+        null,
+        null,
+        null
+    );
+
+    final KafkaEmitter kafkaEmitter = initKafkaEmitter(kafkaEmitterConfig);
+
+    final List<Event> inputEvents = flattenEvents(
+        SERVICE_METRIC_EVENTS,
+        ALERT_EVENTS
+    );
+    final CountDownLatch eventLatch = new CountDownLatch(inputEvents.size());
+
+    final Map<String, List<String>> feedToExpectedEvents = trackExpectedEventsPerFeed(
+        inputEvents,
+        kafkaEmitterConfig.getClusterName(),
+        kafkaEmitterConfig.getExtraDimensions()
+    );
+    final Map<String, List<String>> feedToActualEvents = trackActualEventsPerFeed(eventLatch);
+
+    emitEvents(kafkaEmitter, inputEvents, eventLatch);
+
+    validateEvents(feedToExpectedEvents, feedToActualEvents);
+
+    Assert.assertEquals(0, kafkaEmitter.getMetricLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getAlertLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getSegmentMetadataLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getSegmentMetadataLostCount());

Review Comment:
   ```suggestion
       Assert.assertEquals(0, kafkaEmitter.getRequestLostCount()());
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] Clean up kafka emitter tests, add more validations and code coverage. (druid)

Posted by "abhishekrb19 (via GitHub)" <gi...@apache.org>.
abhishekrb19 commented on code in PR #15878:
URL: https://github.com/apache/druid/pull/15878#discussion_r1488060873


##########
extensions-contrib/kafka-emitter/src/test/java/org/apache/druid/emitter/kafka/KafkaEmitterTest.java:
##########
@@ -19,95 +19,459 @@
 
 package org.apache.druid.emitter.kafka;
 
+import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.datatype.joda.JodaModule;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
+import org.apache.druid.jackson.DefaultObjectMapper;
 import org.apache.druid.java.util.common.DateTimes;
+import org.apache.druid.java.util.common.StringUtils;
 import org.apache.druid.java.util.emitter.core.Event;
+import org.apache.druid.java.util.emitter.core.EventMap;
 import org.apache.druid.java.util.emitter.service.AlertEvent;
 import org.apache.druid.java.util.emitter.service.SegmentMetadataEvent;
 import org.apache.druid.java.util.emitter.service.ServiceMetricEvent;
 import org.apache.druid.server.QueryStats;
 import org.apache.druid.server.RequestLogLine;
 import org.apache.druid.server.log.DefaultRequestLogEventBuilderFactory;
-import org.apache.druid.server.log.RequestLogEvent;
 import org.apache.kafka.clients.producer.KafkaProducer;
 import org.apache.kafka.clients.producer.Producer;
+import org.apache.kafka.clients.producer.ProducerConfig;
+import org.apache.kafka.clients.producer.ProducerRecord;
+import org.junit.After;
 import org.junit.Assert;
+import org.junit.Before;
 import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
 
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
-import java.util.Set;
+import java.util.Map;
 import java.util.concurrent.CountDownLatch;
 
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
-@RunWith(Parameterized.class)
 public class KafkaEmitterTest
 {
-  @Parameterized.Parameter(0)
-  public Set<KafkaEmitterConfig.EventType> eventsType;
+  private KafkaProducer<String, String> producer;
 
-  @Parameterized.Parameter(1)
-  public String requestTopic;
+  @Before
+  public void setup()
+  {
+    producer = mock(KafkaProducer.class);
+  }
 
-  @Parameterized.Parameters(name = "{index}: eventTypes - {0}, requestTopic - {1}")
-  public static Object[] data()
+  @After
+  public void tearDown()
   {
-    return new Object[][] {
-        {new HashSet<>(Arrays.asList(KafkaEmitterConfig.EventType.METRICS, KafkaEmitterConfig.EventType.REQUESTS, KafkaEmitterConfig.EventType.ALERTS, KafkaEmitterConfig.EventType.SEGMENT_METADATA)), "requests"},
-        {new HashSet<>(Arrays.asList(KafkaEmitterConfig.EventType.METRICS, KafkaEmitterConfig.EventType.ALERTS, KafkaEmitterConfig.EventType.SEGMENT_METADATA)), null}
-    };
+    producer.close();
+  }
+
+  private static final ObjectMapper MAPPER = new DefaultObjectMapper();
+
+  private static final List<Event> SERVICE_METRIC_EVENTS = ImmutableList.of(
+      ServiceMetricEvent.builder().setMetric("m1", 1).build("service1", "host1"),
+      ServiceMetricEvent.builder().setMetric("m2", 100).build("service2", "host1"),
+      ServiceMetricEvent.builder().setMetric("m3", 200).build("service2", "host1"),
+      ServiceMetricEvent.builder().setMetric("m1", 150).build("service2", "host2"),
+      ServiceMetricEvent.builder().setMetric("m5", 250).build("service3", "host2")
+  );
+
+  private static final List<Event> ALERT_EVENTS = ImmutableList.of(
+      new AlertEvent("service1", "host1", "description"),
+      new AlertEvent("service2", "host2", "description")
+  );
+
+  private static final List<Event> REQUEST_LOG_EVENTS = ImmutableList.of(
+      DefaultRequestLogEventBuilderFactory.instance().createRequestLogEventBuilder(
+          "requests",
+          RequestLogLine.forSql(
+              "sql1", null, DateTimes.nowUtc(), null, new QueryStats(ImmutableMap.of())
+          )
+      ).build("service", "host"),
+      DefaultRequestLogEventBuilderFactory.instance().createRequestLogEventBuilder(
+          "requests",
+          RequestLogLine.forSql(
+              "sql2", null, DateTimes.nowUtc(), null, new QueryStats(ImmutableMap.of())
+          )
+      ).build("service", "host")
+  );
+
+  private static final List<Event> SEGMENT_METADATA_EVENTS = ImmutableList.of(
+      new SegmentMetadataEvent(
+          "ds1",
+          DateTimes.of("2001-01-01T00:00:00.000Z"),
+          DateTimes.of("2001-01-02T00:00:00.000Z"),
+          DateTimes.of("2001-01-03T00:00:00.000Z"),
+          "ds1",
+          true
+      ),
+      new SegmentMetadataEvent(
+          "ds2",
+          DateTimes.of("2020-01-01T00:00:00.000Z"),
+          DateTimes.of("2020-01-02T00:00:00.000Z"),
+          DateTimes.of("2020-01-03T00:00:00.000Z"),
+          "ds2",
+          true
+      )
+  );
+
+  private static final List<Event> UNKNOWN_EVENTS = ImmutableList.of(
+      new TestEvent(),
+      new TestEvent(),
+      new TestEvent()
+  );
+
+  @Test(timeout = 10_000)
+  public void testServiceMetricEvents() throws JsonProcessingException, InterruptedException
+  {
+    final KafkaEmitterConfig kafkaEmitterConfig = new KafkaEmitterConfig(
+        "",
+        new HashSet<>(Collections.singletonList(KafkaEmitterConfig.EventType.METRICS)),
+        "metrics",
+        "alerts",
+        "requests",
+        "segments",
+        "clusterName",
+        ImmutableMap.of("clusterId", "cluster-101"),
+        null,
+        null
+    );
+
+    final KafkaEmitter kafkaEmitter = initKafkaEmitter(kafkaEmitterConfig);
+
+    final List<Event> inputEvents = flattenEvents(SERVICE_METRIC_EVENTS);
+    final CountDownLatch eventLatch = new CountDownLatch(inputEvents.size());
+
+    final Map<String, List<String>> feedToExpectedEvents = trackExpectedEventsPerFeed(
+        inputEvents,
+        kafkaEmitterConfig.getClusterName(),
+        kafkaEmitterConfig.getExtraDimensions()
+    );
+    final Map<String, List<String>> feedToActualEvents = trackActualEventsPerFeed(eventLatch);
+
+    emitEvents(kafkaEmitter, inputEvents, eventLatch);
+
+    validateEvents(feedToExpectedEvents, feedToActualEvents);
+
+    Assert.assertEquals(0, kafkaEmitter.getMetricLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getAlertLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getSegmentMetadataLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getSegmentMetadataLostCount());

Review Comment:
   Yes, good catch. Thanks for fixing it up in https://github.com/apache/druid/pull/15890



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] Clean up kafka emitter tests, add more validations and code coverage. (druid)

Posted by "zachjsh (via GitHub)" <gi...@apache.org>.
zachjsh merged PR #15878:
URL: https://github.com/apache/druid/pull/15878


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] Clean up kafka emitter tests, add more validations and code coverage. (druid)

Posted by "zachjsh (via GitHub)" <gi...@apache.org>.
zachjsh commented on PR #15878:
URL: https://github.com/apache/druid/pull/15878#issuecomment-1939129684

   Great addition with the new tests. Only thing I would say is would be good to add description of the new tests you added in kafkaEmitterTest; what the test is testing and what the expectations are. Great stuff!


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] Clean up kafka emitter tests, add more validations and code coverage. (druid)

Posted by "TSFenwick (via GitHub)" <gi...@apache.org>.
TSFenwick commented on code in PR #15878:
URL: https://github.com/apache/druid/pull/15878#discussion_r1486553218


##########
extensions-contrib/kafka-emitter/src/test/java/org/apache/druid/emitter/kafka/KafkaEmitterTest.java:
##########
@@ -19,95 +19,459 @@
 
 package org.apache.druid.emitter.kafka;
 
+import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.datatype.joda.JodaModule;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
+import org.apache.druid.jackson.DefaultObjectMapper;
 import org.apache.druid.java.util.common.DateTimes;
+import org.apache.druid.java.util.common.StringUtils;
 import org.apache.druid.java.util.emitter.core.Event;
+import org.apache.druid.java.util.emitter.core.EventMap;
 import org.apache.druid.java.util.emitter.service.AlertEvent;
 import org.apache.druid.java.util.emitter.service.SegmentMetadataEvent;
 import org.apache.druid.java.util.emitter.service.ServiceMetricEvent;
 import org.apache.druid.server.QueryStats;
 import org.apache.druid.server.RequestLogLine;
 import org.apache.druid.server.log.DefaultRequestLogEventBuilderFactory;
-import org.apache.druid.server.log.RequestLogEvent;
 import org.apache.kafka.clients.producer.KafkaProducer;
 import org.apache.kafka.clients.producer.Producer;
+import org.apache.kafka.clients.producer.ProducerConfig;
+import org.apache.kafka.clients.producer.ProducerRecord;
+import org.junit.After;
 import org.junit.Assert;
+import org.junit.Before;
 import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
 
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
-import java.util.Set;
+import java.util.Map;
 import java.util.concurrent.CountDownLatch;
 
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
-@RunWith(Parameterized.class)
 public class KafkaEmitterTest
 {
-  @Parameterized.Parameter(0)
-  public Set<KafkaEmitterConfig.EventType> eventsType;
+  private KafkaProducer<String, String> producer;
 
-  @Parameterized.Parameter(1)
-  public String requestTopic;
+  @Before
+  public void setup()
+  {
+    producer = mock(KafkaProducer.class);
+  }
 
-  @Parameterized.Parameters(name = "{index}: eventTypes - {0}, requestTopic - {1}")
-  public static Object[] data()
+  @After
+  public void tearDown()
   {
-    return new Object[][] {
-        {new HashSet<>(Arrays.asList(KafkaEmitterConfig.EventType.METRICS, KafkaEmitterConfig.EventType.REQUESTS, KafkaEmitterConfig.EventType.ALERTS, KafkaEmitterConfig.EventType.SEGMENT_METADATA)), "requests"},
-        {new HashSet<>(Arrays.asList(KafkaEmitterConfig.EventType.METRICS, KafkaEmitterConfig.EventType.ALERTS, KafkaEmitterConfig.EventType.SEGMENT_METADATA)), null}
-    };
+    producer.close();
+  }
+
+  private static final ObjectMapper MAPPER = new DefaultObjectMapper();
+
+  private static final List<Event> SERVICE_METRIC_EVENTS = ImmutableList.of(
+      ServiceMetricEvent.builder().setMetric("m1", 1).build("service1", "host1"),
+      ServiceMetricEvent.builder().setMetric("m2", 100).build("service2", "host1"),
+      ServiceMetricEvent.builder().setMetric("m3", 200).build("service2", "host1"),
+      ServiceMetricEvent.builder().setMetric("m1", 150).build("service2", "host2"),
+      ServiceMetricEvent.builder().setMetric("m5", 250).build("service3", "host2")
+  );
+
+  private static final List<Event> ALERT_EVENTS = ImmutableList.of(
+      new AlertEvent("service1", "host1", "description"),
+      new AlertEvent("service2", "host2", "description")
+  );
+
+  private static final List<Event> REQUEST_LOG_EVENTS = ImmutableList.of(
+      DefaultRequestLogEventBuilderFactory.instance().createRequestLogEventBuilder(
+          "requests",
+          RequestLogLine.forSql(
+              "sql1", null, DateTimes.nowUtc(), null, new QueryStats(ImmutableMap.of())
+          )
+      ).build("service", "host"),
+      DefaultRequestLogEventBuilderFactory.instance().createRequestLogEventBuilder(
+          "requests",
+          RequestLogLine.forSql(
+              "sql2", null, DateTimes.nowUtc(), null, new QueryStats(ImmutableMap.of())
+          )
+      ).build("service", "host")
+  );
+
+  private static final List<Event> SEGMENT_METADATA_EVENTS = ImmutableList.of(
+      new SegmentMetadataEvent(
+          "ds1",
+          DateTimes.of("2001-01-01T00:00:00.000Z"),
+          DateTimes.of("2001-01-02T00:00:00.000Z"),
+          DateTimes.of("2001-01-03T00:00:00.000Z"),
+          "ds1",
+          true
+      ),
+      new SegmentMetadataEvent(
+          "ds2",
+          DateTimes.of("2020-01-01T00:00:00.000Z"),
+          DateTimes.of("2020-01-02T00:00:00.000Z"),
+          DateTimes.of("2020-01-03T00:00:00.000Z"),
+          "ds2",
+          true
+      )
+  );
+
+  private static final List<Event> UNKNOWN_EVENTS = ImmutableList.of(
+      new TestEvent(),
+      new TestEvent(),
+      new TestEvent()
+  );
+
+  @Test(timeout = 10_000)
+  public void testServiceMetricEvents() throws JsonProcessingException, InterruptedException
+  {
+    final KafkaEmitterConfig kafkaEmitterConfig = new KafkaEmitterConfig(
+        "",
+        new HashSet<>(Collections.singletonList(KafkaEmitterConfig.EventType.METRICS)),
+        "metrics",
+        "alerts",
+        "requests",
+        "segments",
+        "clusterName",
+        ImmutableMap.of("clusterId", "cluster-101"),
+        null,
+        null
+    );
+
+    final KafkaEmitter kafkaEmitter = initKafkaEmitter(kafkaEmitterConfig);
+
+    final List<Event> inputEvents = flattenEvents(SERVICE_METRIC_EVENTS);
+    final CountDownLatch eventLatch = new CountDownLatch(inputEvents.size());
+
+    final Map<String, List<String>> feedToExpectedEvents = trackExpectedEventsPerFeed(
+        inputEvents,
+        kafkaEmitterConfig.getClusterName(),
+        kafkaEmitterConfig.getExtraDimensions()
+    );
+    final Map<String, List<String>> feedToActualEvents = trackActualEventsPerFeed(eventLatch);
+
+    emitEvents(kafkaEmitter, inputEvents, eventLatch);
+
+    validateEvents(feedToExpectedEvents, feedToActualEvents);
+
+    Assert.assertEquals(0, kafkaEmitter.getMetricLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getAlertLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getSegmentMetadataLostCount());
+    Assert.assertEquals(0, kafkaEmitter.getSegmentMetadataLostCount());

Review Comment:
   ```suggestion
       Assert.assertEquals(0, kafkaEmitter.getRequestLostCount()());
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org