markap14 commented on code in PR #11537:
URL: https://github.com/apache/nifi/pull/11537#discussion_r3799119345
##########
nifi-extension-bundles/nifi-kafka-bundle/nifi-kafka-processors/src/main/java/org/apache/nifi/kafka/processors/ConsumeKafka.java:
##########
@@ -274,6 +278,17 @@ public class ConsumeKafka extends AbstractProcessor
implements VerifiableProcess
.dependsOn(PROCESSING_STRATEGY, ProcessingStrategy.RECORD)
.build();
+ static final PropertyDescriptor SCHEMA_CONFLICT_RESOLUTION = new
PropertyDescriptor.Builder()
+ .name("Schema Conflict Resolution")
+ .description("Specifies how to handle records with different
schemas within the same topic and partition. "
+ + "When set to Create New FlowFile, a new FlowFile is
created for each distinct schema. "
+ + "When set to Continue with Merged Schema, all schemas
within a group are merged so that records are batched into a single FlowFile.")
Review Comment:
We should avoid documenting what each individual value does in the Property
description. That information should live in the description of each individual
Allowable Value.
##########
nifi-extension-bundles/nifi-kafka-bundle/nifi-kafka-processors/src/main/java/org/apache/nifi/kafka/processors/ConsumeKafka.java:
##########
@@ -274,6 +278,17 @@ public class ConsumeKafka extends AbstractProcessor
implements VerifiableProcess
.dependsOn(PROCESSING_STRATEGY, ProcessingStrategy.RECORD)
.build();
+ static final PropertyDescriptor SCHEMA_CONFLICT_RESOLUTION = new
PropertyDescriptor.Builder()
+ .name("Schema Conflict Resolution")
+ .description("Specifies how to handle records with different
schemas within the same topic and partition. "
Review Comment:
I think this sentence is lacking detail. Given this description, it sounds
as if all FlowFiles for a given topic & partition should have the same schema,
but that's not the case. Perhaps it should read `Specifies how to handle
records with different schemas within the same output FlowFile`?
##########
nifi-commons/nifi-record/src/main/java/org/apache/nifi/serialization/record/util/DataTypeUtils.java:
##########
@@ -1627,6 +1627,7 @@ public static RecordSchema merge(final RecordSchema
thisSchema, final RecordSche
fields.add(field);
}
+ final Set<Integer> matchedFieldIndices = new HashSet<>();
Review Comment:
Not a big deal but given the frequency with which this might get called,
it's best to keep this as efficient as we can. So I would suggest using a
`BitSet` rather than a `Set<Integer>`
##########
nifi-extension-bundles/nifi-kafka-bundle/nifi-kafka-processors/src/main/java/org/apache/nifi/kafka/processors/consumer/convert/MergeSchemaGrouping.java:
##########
@@ -0,0 +1,155 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.nifi.kafka.processors.consumer.convert;
+
+import org.apache.nifi.flowfile.FlowFile;
+import org.apache.nifi.flowfile.attributes.CoreAttributes;
+import org.apache.nifi.kafka.processors.ConsumeKafka;
+import org.apache.nifi.kafka.service.api.record.ByteRecord;
+import org.apache.nifi.kafka.shared.attribute.KafkaFlowFileAttribute;
+import org.apache.nifi.logging.ComponentLog;
+import org.apache.nifi.processor.ProcessSession;
+import org.apache.nifi.processor.exception.ProcessException;
+import org.apache.nifi.schema.access.SchemaNotFoundException;
+import org.apache.nifi.serialization.RecordSetWriter;
+import org.apache.nifi.serialization.RecordSetWriterFactory;
+import org.apache.nifi.serialization.WriteResult;
+import org.apache.nifi.serialization.record.Record;
+import org.apache.nifi.serialization.record.RecordSchema;
+import org.apache.nifi.serialization.record.util.DataTypeUtils;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Continue with Merged Schema strategy: groups by topic, partition, and
grouping attributes,
+ * merging per-record write schemas and writing once per group.
+ */
+public class MergeSchemaGrouping implements RecordGroupingStrategy {
+
+ private final RecordSetWriterFactory writerFactory;
+ private final ComponentLog logger;
+ private final String brokerUri;
+ private final boolean commitOffsets;
+ private final Map<MergeGroupKey, MergeGroup> mergeGroups = new HashMap<>();
+
+ public MergeSchemaGrouping(
+ final RecordSetWriterFactory writerFactory,
+ final ComponentLog logger,
+ final String brokerUri,
+ final boolean commitOffsets) {
+ this.writerFactory = writerFactory;
+ this.logger = logger;
+ this.brokerUri = brokerUri;
+ this.commitOffsets = commitOffsets;
+ }
+
+ @Override
+ public void addRecord(
+ final ProcessSession session,
+ final ByteRecord consumerRecord,
+ final Record recordToWrite,
+ final RecordSchema writeSchema,
+ final Map<String, String> attributes,
+ final Map<String, String> groupingAttributes) {
+ final MergeGroupKey key = new MergeGroupKey(groupingAttributes,
consumerRecord.getTopic(), consumerRecord.getPartition());
+ final MergeGroup group = mergeGroups.computeIfAbsent(key, ignored ->
new MergeGroup(attributes));
+ group.add(recordToWrite, writeSchema, consumerRecord);
+ }
+
+ @Override
+ public void finishAllGroups(final ProcessSession session) {
+ for (final Map.Entry<MergeGroupKey, MergeGroup> entry :
mergeGroups.entrySet()) {
+ final MergeGroupKey key = entry.getKey();
+ final MergeGroup group = entry.getValue();
+
+ FlowFile flowFile = session.create();
+
+ final RecordSchema schemaToWrite;
+ try {
+ schemaToWrite = writerFactory.getSchema(group.attributes,
group.mergedWriteSchema);
+ } catch (final SchemaNotFoundException | IOException e) {
+ throw new ProcessException("Failed to determine write schema
for Kafka records", e);
+ }
+
+ final Map<String, String> flowFileAttributes = new HashMap<>();
+ final int[] recordCountHolder = new int[1];
Review Comment:
This is a bad practice - should prefer using `final AtomicInteger` instead.
##########
nifi-extension-bundles/nifi-kafka-bundle/nifi-kafka-processors/src/main/java/org/apache/nifi/kafka/processors/consumer/convert/RecordGroupingStrategy.java:
##########
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.nifi.kafka.processors.consumer.convert;
+
+import org.apache.nifi.kafka.service.api.record.ByteRecord;
+import org.apache.nifi.processor.ProcessSession;
+import org.apache.nifi.serialization.record.Record;
+import org.apache.nifi.serialization.record.RecordSchema;
+
+import java.util.Map;
+
+/**
+ * Groups converted Kafka records into FlowFiles according to a Schema
Conflict Resolution strategy.
+ * <p>
+ * Implementations are stateful: they accumulate open writers or buffered
records until
+ * {@link #finishAllGroups(ProcessSession)} is called. A new instance must be
created for each
+ * {@code onTrigger} invocation and must not be reused across calls, so that
leftover group state
+ * cannot survive an exception or a failed session.
+ */
+public interface RecordGroupingStrategy {
+
+ void addRecord(
+ ProcessSession session,
+ ByteRecord consumerRecord,
+ Record recordToWrite,
+ RecordSchema writeSchema,
+ Map<String, String> attributes,
+ Map<String, String> groupingAttributes) throws Exception;
Review Comment:
We should avoid throwing the general `Exception`
##########
nifi-extension-bundles/nifi-kafka-bundle/nifi-kafka-3-integration/src/test/java/org/apache/nifi/kafka/processors/ConsumeKafkaMergeSchemaIT.java:
##########
@@ -0,0 +1,310 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.nifi.kafka.processors;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import org.apache.kafka.clients.admin.AdminClient;
+import org.apache.kafka.clients.admin.AdminClientConfig;
+import org.apache.kafka.clients.admin.NewTopic;
+import org.apache.kafka.clients.producer.ProducerRecord;
+import org.apache.kafka.common.header.Header;
+import org.apache.nifi.kafka.processors.consumer.ProcessingStrategy;
+import org.apache.nifi.kafka.service.api.consumer.AutoOffsetReset;
+import org.apache.nifi.kafka.shared.attribute.KafkaFlowFileAttribute;
+import org.apache.nifi.kafka.shared.property.OutputStrategy;
+import org.apache.nifi.kafka.shared.property.SchemaConflictResolution;
+import org.apache.nifi.reporting.InitializationException;
+import org.apache.nifi.util.MockFlowFile;
+import org.apache.nifi.util.TestRunner;
+import org.apache.nifi.util.TestRunners;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.ExecutionException;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class ConsumeKafkaMergeSchemaIT extends AbstractConsumeKafkaIT {
+
+ private static final int FIRST_PARTITION = 0;
+
+ private static final String RECORD_WITH_ID = """
+ { "id": 1 }
+ """;
+
+ private static final String RECORD_WITH_NAME = """
+ { "name": "Alice" }
+ """;
+
+ private static final String INVALID_RECORD = "not-valid-json";
+
+ private TestRunner runner;
+
+ @BeforeEach
+ void setRunner() throws InitializationException {
+ runner = TestRunners.newTestRunner(ConsumeKafka.class);
+ addKafkaConnectionService(runner);
+ runner.setProperty(ConsumeKafka.CONNECTION_SERVICE,
CONNECTION_SERVICE_ID);
+ addRecordReaderService(runner);
+ addRecordWriterService(runner);
+ }
+
+ @Test
+ void testMergedSchemaProducesSingleFlowFile() throws ExecutionException,
InterruptedException, IOException {
+ final String topic = UUID.randomUUID().toString();
+ final String groupId = topic.substring(0, topic.indexOf("-"));
+
+ runner.setProperty(ConsumeKafka.GROUP_ID, groupId);
+ runner.setProperty(ConsumeKafka.TOPICS, topic);
+ runner.setProperty(ConsumeKafka.PROCESSING_STRATEGY,
ProcessingStrategy.RECORD.getValue());
+ runner.setProperty(ConsumeKafka.OUTPUT_STRATEGY,
OutputStrategy.USE_VALUE.getValue());
+ runner.setProperty(ConsumeKafka.SCHEMA_CONFLICT_RESOLUTION,
SchemaConflictResolution.CONTINUE_WITH_MERGED_SCHEMA.getValue());
+ runner.setProperty(ConsumeKafka.AUTO_OFFSET_RESET,
AutoOffsetReset.EARLIEST.getValue());
+
+ runner.run(1, false, true);
+
+ produce(topic, List.of(
+ new ProducerRecord<>(topic, FIRST_PARTITION, (String) null,
RECORD_WITH_ID, List.<Header>of()),
+ new ProducerRecord<>(topic, FIRST_PARTITION, (String) null,
RECORD_WITH_NAME, List.<Header>of())));
+
+ while
(runner.getFlowFilesForRelationship(ConsumeKafka.SUCCESS).isEmpty()) {
+ runner.run(1, false, false);
+ }
+
+ runner.run(1, true, false);
+
+ final List<MockFlowFile> successFlowFiles =
runner.getFlowFilesForRelationship(ConsumeKafka.SUCCESS);
+ assertEquals(1, successFlowFiles.size());
+
+ final MockFlowFile flowFile = successFlowFiles.getFirst();
+ flowFile.assertAttributeEquals(KafkaFlowFileAttribute.KAFKA_TOPIC,
topic);
+ flowFile.assertAttributeEquals(KafkaFlowFileAttribute.KAFKA_PARTITION,
Integer.toString(FIRST_PARTITION));
+ flowFile.assertAttributeEquals("record.count", "2");
+
+ final JsonNode jsonTree = objectMapper.readTree(flowFile.getContent());
+ final JsonNode expected = objectMapper.readTree("""
+ [
+ { "id": 1, "name": null },
+ { "id": null, "name": "Alice" }
+ ]
+ """);
+ assertEquals(expected, jsonTree);
+ }
+
+ @Test
+ void testCreateNewFlowFileDefaultProducesMultipleFlowFiles() throws
ExecutionException, InterruptedException {
+ final String topic = UUID.randomUUID().toString();
+ final String groupId = topic.substring(0, topic.indexOf("-"));
+
+ runner.setProperty(ConsumeKafka.GROUP_ID, groupId);
+ runner.setProperty(ConsumeKafka.TOPICS, topic);
+ runner.setProperty(ConsumeKafka.PROCESSING_STRATEGY,
ProcessingStrategy.RECORD.getValue());
+ runner.setProperty(ConsumeKafka.OUTPUT_STRATEGY,
OutputStrategy.USE_VALUE.getValue());
+ runner.setProperty(ConsumeKafka.AUTO_OFFSET_RESET,
AutoOffsetReset.EARLIEST.getValue());
+
+ runner.run(1, false, true);
+
+ produce(topic, List.of(
+ new ProducerRecord<>(topic, FIRST_PARTITION, (String) null,
RECORD_WITH_ID, List.<Header>of()),
+ new ProducerRecord<>(topic, FIRST_PARTITION, (String) null,
RECORD_WITH_NAME, List.<Header>of())));
+
+ while (runner.getFlowFilesForRelationship(ConsumeKafka.SUCCESS).size()
< 2) {
+ runner.run(1, false, false);
+ }
+
+ runner.run(1, true, false);
+
+ final List<MockFlowFile> successFlowFiles =
runner.getFlowFilesForRelationship(ConsumeKafka.SUCCESS);
+ assertEquals(2, successFlowFiles.size());
+
+ for (final MockFlowFile flowFile : successFlowFiles) {
+ flowFile.assertAttributeEquals(KafkaFlowFileAttribute.KAFKA_TOPIC,
topic);
+
flowFile.assertAttributeEquals(KafkaFlowFileAttribute.KAFKA_PARTITION,
Integer.toString(FIRST_PARTITION));
+ }
+ }
+
+ @Test
+ void testMergedSchemaDifferentPartitionsProduceSeparateFlowFiles() throws
Exception {
+ final String topic = UUID.randomUUID().toString();
+ final String groupId = topic.substring(0, topic.indexOf("-"));
+
+ try (final AdminClient admin = AdminClient.create(
+ Map.of(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG,
kafkaContainer.getBootstrapServers()))) {
+ admin.createTopics(List.of(new NewTopic(topic, 2, (short)
1))).all().get();
+ }
+
+ runner.setProperty(ConsumeKafka.GROUP_ID, groupId);
+ runner.setProperty(ConsumeKafka.TOPICS, topic);
+ runner.setProperty(ConsumeKafka.PROCESSING_STRATEGY,
ProcessingStrategy.RECORD.getValue());
+ runner.setProperty(ConsumeKafka.OUTPUT_STRATEGY,
OutputStrategy.USE_VALUE.getValue());
+ runner.setProperty(ConsumeKafka.SCHEMA_CONFLICT_RESOLUTION,
SchemaConflictResolution.CONTINUE_WITH_MERGED_SCHEMA.getValue());
+ runner.setProperty(ConsumeKafka.AUTO_OFFSET_RESET,
AutoOffsetReset.EARLIEST.getValue());
+
+ runner.run(1, false, true);
+
+ // Publish as one producer batch so the records are available together
for a single poll/onTrigger.
+ produce(topic, List.of(
+ new ProducerRecord<>(topic, 0, (String) null, RECORD_WITH_ID,
List.<Header>of()),
+ new ProducerRecord<>(topic, 0, (String) null,
RECORD_WITH_NAME, List.<Header>of()),
+ new ProducerRecord<>(topic, 1, (String) null,
RECORD_WITH_NAME, List.<Header>of())));
+
+ while
(totalRecordCount(runner.getFlowFilesForRelationship(ConsumeKafka.SUCCESS)) <
3) {
+ runner.run(1, false, false);
+ }
+
+ runner.run(1, true, false);
+
+ final List<MockFlowFile> successFlowFiles =
runner.getFlowFilesForRelationship(ConsumeKafka.SUCCESS);
+ assertEquals(3, totalRecordCount(successFlowFiles));
+
+ final List<MockFlowFile> partitionZero = successFlowFiles.stream()
+ .filter(ff ->
"0".equals(ff.getAttribute(KafkaFlowFileAttribute.KAFKA_PARTITION)))
+ .toList();
+ final List<MockFlowFile> partitionOne = successFlowFiles.stream()
+ .filter(ff ->
"1".equals(ff.getAttribute(KafkaFlowFileAttribute.KAFKA_PARTITION)))
+ .toList();
+
+ assertEquals(1, partitionZero.size());
+ assertEquals(1, partitionOne.size());
+ assertEquals(2, totalRecordCount(partitionZero));
+ assertEquals(1, totalRecordCount(partitionOne));
+ // Records from different partitions never share a FlowFile.
+ assertTrue(partitionZero.stream().noneMatch(ff ->
"1".equals(ff.getAttribute(KafkaFlowFileAttribute.KAFKA_PARTITION))));
+ }
+
+ private static int totalRecordCount(final List<MockFlowFile> flowFiles) {
+ return flowFiles.stream()
+ .mapToInt(ff ->
Integer.parseInt(ff.getAttribute("record.count")))
+ .sum();
+ }
+
+ @Test
+ void testMergedSchemaWithParseFailure() throws ExecutionException,
InterruptedException, IOException {
+ final String topic = UUID.randomUUID().toString();
+ final String groupId = topic.substring(0, topic.indexOf("-"));
+
+ runner.setProperty(ConsumeKafka.GROUP_ID, groupId);
+ runner.setProperty(ConsumeKafka.TOPICS, topic);
+ runner.setProperty(ConsumeKafka.PROCESSING_STRATEGY,
ProcessingStrategy.RECORD.getValue());
+ runner.setProperty(ConsumeKafka.OUTPUT_STRATEGY,
OutputStrategy.USE_VALUE.getValue());
+ runner.setProperty(ConsumeKafka.SCHEMA_CONFLICT_RESOLUTION,
SchemaConflictResolution.CONTINUE_WITH_MERGED_SCHEMA.getValue());
+ runner.setProperty(ConsumeKafka.AUTO_OFFSET_RESET,
AutoOffsetReset.EARLIEST.getValue());
+
+ runner.run(1, false, true);
+
+ produce(topic, List.of(
+ new ProducerRecord<>(topic, FIRST_PARTITION, (String) null,
RECORD_WITH_ID, List.<Header>of()),
+ new ProducerRecord<>(topic, FIRST_PARTITION, (String) null,
INVALID_RECORD, List.<Header>of()),
+ new ProducerRecord<>(topic, FIRST_PARTITION, (String) null,
RECORD_WITH_NAME, List.<Header>of())));
+
+ while
(runner.getFlowFilesForRelationship(ConsumeKafka.SUCCESS).isEmpty()) {
Review Comment:
This can potentially block forever; should fail after some time period or
number of attempts
##########
nifi-extension-bundles/nifi-kafka-bundle/nifi-kafka-processors/src/main/java/org/apache/nifi/kafka/processors/consumer/convert/CreateNewFlowFileGrouping.java:
##########
@@ -0,0 +1,164 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.nifi.kafka.processors.consumer.convert;
+
+import org.apache.nifi.flowfile.FlowFile;
+import org.apache.nifi.flowfile.attributes.CoreAttributes;
+import org.apache.nifi.kafka.processors.ConsumeKafka;
+import org.apache.nifi.kafka.service.api.record.ByteRecord;
+import org.apache.nifi.kafka.shared.attribute.KafkaFlowFileAttribute;
+import org.apache.nifi.logging.ComponentLog;
+import org.apache.nifi.processor.ProcessSession;
+import org.apache.nifi.processor.exception.ProcessException;
+import org.apache.nifi.serialization.RecordSetWriter;
+import org.apache.nifi.serialization.RecordSetWriterFactory;
+import org.apache.nifi.serialization.WriteResult;
+import org.apache.nifi.serialization.record.Record;
+import org.apache.nifi.serialization.record.RecordSchema;
+
+import java.io.OutputStream;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicLong;
+
+/**
+ * Create New FlowFile strategy: groups by write schema, topic, partition, and
grouping attributes,
+ * streaming records into an open writer per group.
+ */
+public class CreateNewFlowFileGrouping implements RecordGroupingStrategy {
+
+ private final RecordSetWriterFactory writerFactory;
+ private final ComponentLog logger;
+ private final String brokerUri;
+ private final boolean commitOffsets;
+ private final Map<RecordGroupCriteria, RecordGroup> recordGroups = new
HashMap<>();
+
+ public CreateNewFlowFileGrouping(
+ final RecordSetWriterFactory writerFactory,
+ final ComponentLog logger,
+ final String brokerUri,
+ final boolean commitOffsets) {
+ this.writerFactory = writerFactory;
+ this.logger = logger;
+ this.brokerUri = brokerUri;
+ this.commitOffsets = commitOffsets;
+ }
+
+ @Override
+ public void addRecord(
+ final ProcessSession session,
+ final ByteRecord consumerRecord,
+ final Record recordToWrite,
+ final RecordSchema writeSchema,
+ final Map<String, String> attributes,
+ final Map<String, String> groupingAttributes) throws Exception {
+ final String topic = consumerRecord.getTopic();
+ final int partition = consumerRecord.getPartition();
+
+ final RecordGroupCriteria criteria = new
RecordGroupCriteria(writeSchema, groupingAttributes, topic, partition);
+ RecordGroup group = recordGroups.get(criteria);
+ if (group == null) {
+ FlowFile ff = session.create();
+ ff = session.putAllAttributes(ff, Map.of(
+ KafkaFlowFileAttribute.KAFKA_TOPIC, topic,
+ KafkaFlowFileAttribute.KAFKA_PARTITION,
String.valueOf(partition)));
+
+ final OutputStream out = session.write(ff);
+ final RecordSetWriter writer;
+ try {
+ writer = writerFactory.createWriter(logger, writeSchema, out,
attributes);
+ writer.beginRecordSet();
+ } catch (final Exception ex) {
+ out.close();
+ throw ex;
+ }
+
+ final long offset = consumerRecord.getOffset();
+ final AtomicLong maxOffset = new AtomicLong(offset);
+ final AtomicLong minOffset = new AtomicLong(offset);
+ final AtomicLong minTimestamp = new
AtomicLong(consumerRecord.getTimestamp());
+ group = new RecordGroup(ff, writer, maxOffset, minOffset,
minTimestamp);
+ recordGroups.put(criteria, group);
+ } else {
+ final long recordOffset = consumerRecord.getOffset();
+ final AtomicLong maxOffset = group.maxOffset();
+ if (recordOffset > maxOffset.get()) {
+ maxOffset.set(recordOffset);
+ }
+
+ final AtomicLong minOffset = group.minOffset();
+ if (recordOffset < minOffset.get()) {
+ minOffset.set(recordOffset);
+ }
+
+ final long recordTimestamp = consumerRecord.getTimestamp();
+ final AtomicLong minTimestamp = group.minTimestamp();
+ if (recordTimestamp < minTimestamp.get()) {
+ minTimestamp.set(recordTimestamp);
+ }
+ }
+
+ group.writer().write(recordToWrite);
+ }
+
+ @Override
+ public void finishAllGroups(final ProcessSession session) {
+ for (final Map.Entry<RecordGroupCriteria, RecordGroup> e :
recordGroups.entrySet()) {
+ final RecordGroupCriteria criteria = e.getKey();
+ final RecordGroup group = e.getValue();
+
+ final Map<String, String> resultAttrs = new HashMap<>();
+ final int recordCount;
+ try (final RecordSetWriter writer = group.writer()) {
+ final WriteResult wr = writer.finishRecordSet();
Review Comment:
Should avoid shorthand, `writeResult` rather than `wr`
##########
nifi-extension-bundles/nifi-kafka-bundle/nifi-kafka-3-integration/src/test/java/org/apache/nifi/kafka/processors/ConsumeKafkaMergeSchemaIT.java:
##########
@@ -0,0 +1,310 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.nifi.kafka.processors;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import org.apache.kafka.clients.admin.AdminClient;
+import org.apache.kafka.clients.admin.AdminClientConfig;
+import org.apache.kafka.clients.admin.NewTopic;
+import org.apache.kafka.clients.producer.ProducerRecord;
+import org.apache.kafka.common.header.Header;
+import org.apache.nifi.kafka.processors.consumer.ProcessingStrategy;
+import org.apache.nifi.kafka.service.api.consumer.AutoOffsetReset;
+import org.apache.nifi.kafka.shared.attribute.KafkaFlowFileAttribute;
+import org.apache.nifi.kafka.shared.property.OutputStrategy;
+import org.apache.nifi.kafka.shared.property.SchemaConflictResolution;
+import org.apache.nifi.reporting.InitializationException;
+import org.apache.nifi.util.MockFlowFile;
+import org.apache.nifi.util.TestRunner;
+import org.apache.nifi.util.TestRunners;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.ExecutionException;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class ConsumeKafkaMergeSchemaIT extends AbstractConsumeKafkaIT {
+
+ private static final int FIRST_PARTITION = 0;
+
+ private static final String RECORD_WITH_ID = """
+ { "id": 1 }
+ """;
+
+ private static final String RECORD_WITH_NAME = """
+ { "name": "Alice" }
+ """;
+
+ private static final String INVALID_RECORD = "not-valid-json";
+
+ private TestRunner runner;
+
+ @BeforeEach
+ void setRunner() throws InitializationException {
+ runner = TestRunners.newTestRunner(ConsumeKafka.class);
+ addKafkaConnectionService(runner);
+ runner.setProperty(ConsumeKafka.CONNECTION_SERVICE,
CONNECTION_SERVICE_ID);
+ addRecordReaderService(runner);
+ addRecordWriterService(runner);
+ }
+
+ @Test
+ void testMergedSchemaProducesSingleFlowFile() throws ExecutionException,
InterruptedException, IOException {
+ final String topic = UUID.randomUUID().toString();
+ final String groupId = topic.substring(0, topic.indexOf("-"));
+
+ runner.setProperty(ConsumeKafka.GROUP_ID, groupId);
+ runner.setProperty(ConsumeKafka.TOPICS, topic);
+ runner.setProperty(ConsumeKafka.PROCESSING_STRATEGY,
ProcessingStrategy.RECORD.getValue());
+ runner.setProperty(ConsumeKafka.OUTPUT_STRATEGY,
OutputStrategy.USE_VALUE.getValue());
+ runner.setProperty(ConsumeKafka.SCHEMA_CONFLICT_RESOLUTION,
SchemaConflictResolution.CONTINUE_WITH_MERGED_SCHEMA.getValue());
+ runner.setProperty(ConsumeKafka.AUTO_OFFSET_RESET,
AutoOffsetReset.EARLIEST.getValue());
+
+ runner.run(1, false, true);
+
+ produce(topic, List.of(
+ new ProducerRecord<>(topic, FIRST_PARTITION, (String) null,
RECORD_WITH_ID, List.<Header>of()),
+ new ProducerRecord<>(topic, FIRST_PARTITION, (String) null,
RECORD_WITH_NAME, List.<Header>of())));
+
+ while
(runner.getFlowFilesForRelationship(ConsumeKafka.SUCCESS).isEmpty()) {
Review Comment:
This can potentially block forever; should fail after some time period or
number of attempts
##########
nifi-extension-bundles/nifi-kafka-bundle/nifi-kafka-3-integration/src/test/java/org/apache/nifi/kafka/processors/ConsumeKafkaMergeSchemaIT.java:
##########
@@ -0,0 +1,310 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.nifi.kafka.processors;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import org.apache.kafka.clients.admin.AdminClient;
+import org.apache.kafka.clients.admin.AdminClientConfig;
+import org.apache.kafka.clients.admin.NewTopic;
+import org.apache.kafka.clients.producer.ProducerRecord;
+import org.apache.kafka.common.header.Header;
+import org.apache.nifi.kafka.processors.consumer.ProcessingStrategy;
+import org.apache.nifi.kafka.service.api.consumer.AutoOffsetReset;
+import org.apache.nifi.kafka.shared.attribute.KafkaFlowFileAttribute;
+import org.apache.nifi.kafka.shared.property.OutputStrategy;
+import org.apache.nifi.kafka.shared.property.SchemaConflictResolution;
+import org.apache.nifi.reporting.InitializationException;
+import org.apache.nifi.util.MockFlowFile;
+import org.apache.nifi.util.TestRunner;
+import org.apache.nifi.util.TestRunners;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.ExecutionException;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class ConsumeKafkaMergeSchemaIT extends AbstractConsumeKafkaIT {
+
+ private static final int FIRST_PARTITION = 0;
+
+ private static final String RECORD_WITH_ID = """
+ { "id": 1 }
+ """;
+
+ private static final String RECORD_WITH_NAME = """
+ { "name": "Alice" }
+ """;
+
+ private static final String INVALID_RECORD = "not-valid-json";
+
+ private TestRunner runner;
+
+ @BeforeEach
+ void setRunner() throws InitializationException {
+ runner = TestRunners.newTestRunner(ConsumeKafka.class);
+ addKafkaConnectionService(runner);
+ runner.setProperty(ConsumeKafka.CONNECTION_SERVICE,
CONNECTION_SERVICE_ID);
+ addRecordReaderService(runner);
+ addRecordWriterService(runner);
+ }
+
+ @Test
+ void testMergedSchemaProducesSingleFlowFile() throws ExecutionException,
InterruptedException, IOException {
+ final String topic = UUID.randomUUID().toString();
+ final String groupId = topic.substring(0, topic.indexOf("-"));
+
+ runner.setProperty(ConsumeKafka.GROUP_ID, groupId);
+ runner.setProperty(ConsumeKafka.TOPICS, topic);
+ runner.setProperty(ConsumeKafka.PROCESSING_STRATEGY,
ProcessingStrategy.RECORD.getValue());
+ runner.setProperty(ConsumeKafka.OUTPUT_STRATEGY,
OutputStrategy.USE_VALUE.getValue());
+ runner.setProperty(ConsumeKafka.SCHEMA_CONFLICT_RESOLUTION,
SchemaConflictResolution.CONTINUE_WITH_MERGED_SCHEMA.getValue());
+ runner.setProperty(ConsumeKafka.AUTO_OFFSET_RESET,
AutoOffsetReset.EARLIEST.getValue());
+
+ runner.run(1, false, true);
+
+ produce(topic, List.of(
+ new ProducerRecord<>(topic, FIRST_PARTITION, (String) null,
RECORD_WITH_ID, List.<Header>of()),
+ new ProducerRecord<>(topic, FIRST_PARTITION, (String) null,
RECORD_WITH_NAME, List.<Header>of())));
+
+ while
(runner.getFlowFilesForRelationship(ConsumeKafka.SUCCESS).isEmpty()) {
+ runner.run(1, false, false);
+ }
+
+ runner.run(1, true, false);
+
+ final List<MockFlowFile> successFlowFiles =
runner.getFlowFilesForRelationship(ConsumeKafka.SUCCESS);
+ assertEquals(1, successFlowFiles.size());
+
+ final MockFlowFile flowFile = successFlowFiles.getFirst();
+ flowFile.assertAttributeEquals(KafkaFlowFileAttribute.KAFKA_TOPIC,
topic);
+ flowFile.assertAttributeEquals(KafkaFlowFileAttribute.KAFKA_PARTITION,
Integer.toString(FIRST_PARTITION));
+ flowFile.assertAttributeEquals("record.count", "2");
+
+ final JsonNode jsonTree = objectMapper.readTree(flowFile.getContent());
+ final JsonNode expected = objectMapper.readTree("""
+ [
+ { "id": 1, "name": null },
+ { "id": null, "name": "Alice" }
+ ]
+ """);
+ assertEquals(expected, jsonTree);
+ }
+
+ @Test
+ void testCreateNewFlowFileDefaultProducesMultipleFlowFiles() throws
ExecutionException, InterruptedException {
+ final String topic = UUID.randomUUID().toString();
+ final String groupId = topic.substring(0, topic.indexOf("-"));
+
+ runner.setProperty(ConsumeKafka.GROUP_ID, groupId);
+ runner.setProperty(ConsumeKafka.TOPICS, topic);
+ runner.setProperty(ConsumeKafka.PROCESSING_STRATEGY,
ProcessingStrategy.RECORD.getValue());
+ runner.setProperty(ConsumeKafka.OUTPUT_STRATEGY,
OutputStrategy.USE_VALUE.getValue());
+ runner.setProperty(ConsumeKafka.AUTO_OFFSET_RESET,
AutoOffsetReset.EARLIEST.getValue());
+
+ runner.run(1, false, true);
+
+ produce(topic, List.of(
+ new ProducerRecord<>(topic, FIRST_PARTITION, (String) null,
RECORD_WITH_ID, List.<Header>of()),
+ new ProducerRecord<>(topic, FIRST_PARTITION, (String) null,
RECORD_WITH_NAME, List.<Header>of())));
+
+ while (runner.getFlowFilesForRelationship(ConsumeKafka.SUCCESS).size()
< 2) {
Review Comment:
This can potentially block forever; should fail after some time period or
number of attempts
##########
nifi-commons/nifi-record/src/test/java/org/apache/nifi/serialization/record/TestDataTypeUtils.java:
##########
@@ -1392,4 +1397,278 @@ public void
testMergeDataTypesWithManyDistinctRecordSchemasCompletesQuickly() {
assertTrue(finalSchema.getField("field_0").isPresent());
assertTrue(finalSchema.getField("field_4999").isPresent());
}
+
+ @Test
+ public void testMergeSchemasMakesSingleSideFieldsNullable() {
+ final RecordSchema schemaA = new SimpleRecordSchema(List.of(
+ new RecordField("id", RecordFieldType.STRING.getDataType(),
false)));
+ final RecordSchema schemaB = new SimpleRecordSchema(List.of(
+ new RecordField("name", RecordFieldType.STRING.getDataType(),
false)));
+
+ final RecordSchema merged = DataTypeUtils.merge(schemaA, schemaB);
+
+ assertEquals(2, merged.getFieldCount());
+ assertTrue(merged.getField("id").orElseThrow().isNullable());
+ assertTrue(merged.getField("name").orElseThrow().isNullable());
+ }
+
+ @Test
+ public void testMergeSchemasKeepsSharedNonNullableFieldNonNullable() {
+ final RecordSchema schemaA = new SimpleRecordSchema(List.of(
+ new RecordField("id", RecordFieldType.STRING.getDataType(),
false)));
+ final RecordSchema schemaB = new SimpleRecordSchema(List.of(
+ new RecordField("id", RecordFieldType.STRING.getDataType(),
false)));
+
+ final RecordSchema merged = DataTypeUtils.merge(schemaA, schemaB);
+
+ assertEquals(1, merged.getFieldCount());
+ assertFalse(merged.getField("id").orElseThrow().isNullable());
+ }
+
+ @Test
+ public void testMergeSchemasPreservesNullableWhenLeftIsNullable() {
+ final RecordSchema schemaA = new SimpleRecordSchema(List.of(
+ new RecordField("id", RecordFieldType.STRING.getDataType(),
true)));
+ final RecordSchema schemaB = new SimpleRecordSchema(List.of(
+ new RecordField("id", RecordFieldType.STRING.getDataType(),
false)));
+
+ final RecordSchema merged = DataTypeUtils.merge(schemaA, schemaB);
+
+ assertTrue(merged.getField("id").orElseThrow().isNullable());
+ }
+
+ @Test
+ public void testMergeSchemasPreservesNullableWhenRightIsNullable() {
+ final RecordSchema schemaA = new SimpleRecordSchema(List.of(
+ new RecordField("id", RecordFieldType.STRING.getDataType(),
false)));
+ final RecordSchema schemaB = new SimpleRecordSchema(List.of(
+ new RecordField("id", RecordFieldType.STRING.getDataType(),
true)));
+
+ final RecordSchema merged = DataTypeUtils.merge(schemaA, schemaB);
+
+ assertTrue(merged.getField("id").orElseThrow().isNullable());
+ }
+
+ @Test
+ public void testMergeSchemasWidensTypesAndNullifiesSingleSideFields() {
+ final RecordSchema schemaA = new SimpleRecordSchema(List.of(
+ new RecordField("id", RecordFieldType.INT.getDataType(), false),
+ new RecordField("onlyA", RecordFieldType.STRING.getDataType(),
false)));
+ final RecordSchema schemaB = new SimpleRecordSchema(List.of(
+ new RecordField("id", RecordFieldType.LONG.getDataType(), true),
+ new RecordField("onlyB", RecordFieldType.STRING.getDataType(),
Set.of("bAlias"), false)));
+
+ final RecordSchema merged = DataTypeUtils.merge(schemaA, schemaB);
+
+ assertEquals(3, merged.getFieldCount());
+ final RecordField idField = merged.getField("id").orElseThrow();
+ assertEquals(RecordFieldType.LONG,
idField.getDataType().getFieldType());
+ assertTrue(idField.isNullable());
+ assertTrue(merged.getField("onlyA").orElseThrow().isNullable());
+ assertTrue(merged.getField("onlyB").orElseThrow().isNullable());
+ }
+
+ @Test
+ public void testMergeSchemasIdenticalSchemasRetainNullability() {
+ final RecordSchema schemaA = new SimpleRecordSchema(List.of(
+ new RecordField("required", RecordFieldType.STRING.getDataType(),
false),
+ new RecordField("optional", RecordFieldType.INT.getDataType(),
true)));
+ final RecordSchema schemaB = new SimpleRecordSchema(List.of(
+ new RecordField("required", RecordFieldType.STRING.getDataType(),
false),
+ new RecordField("optional", RecordFieldType.INT.getDataType(),
true)));
+
+ final RecordSchema merged = DataTypeUtils.merge(schemaA, schemaB);
+
+ assertEquals(2, merged.getFieldCount());
+ assertFalse(merged.getField("required").orElseThrow().isNullable());
+ assertTrue(merged.getField("optional").orElseThrow().isNullable());
+ }
+
+ @Test
+ public void testMergeSchemasMakesNestedSingleSideFieldsNullable() {
+ final RecordSchema nestedA = new SimpleRecordSchema(List.of(
+ new RecordField("street", RecordFieldType.STRING.getDataType(),
false),
+ new RecordField("city", RecordFieldType.STRING.getDataType(),
false)));
+ final RecordSchema nestedB = new SimpleRecordSchema(List.of(
+ new RecordField("street", RecordFieldType.STRING.getDataType(),
false),
+ new RecordField("zip", RecordFieldType.STRING.getDataType(),
false)));
+
+ final RecordSchema schemaA = new SimpleRecordSchema(List.of(
+ new RecordField("address",
RecordFieldType.RECORD.getRecordDataType(nestedA), false)));
+ final RecordSchema schemaB = new SimpleRecordSchema(List.of(
+ new RecordField("address",
RecordFieldType.RECORD.getRecordDataType(nestedB), false)));
+
+ final RecordSchema merged = DataTypeUtils.merge(schemaA, schemaB);
+ final RecordField addressField =
merged.getField("address").orElseThrow();
+ assertFalse(addressField.isNullable());
+
+ final RecordSchema nestedMerged = ((RecordDataType)
addressField.getDataType()).getChildSchema();
+ assertEquals(3, nestedMerged.getFieldCount());
+
assertFalse(nestedMerged.getField("street").orElseThrow().isNullable());
+ assertTrue(nestedMerged.getField("city").orElseThrow().isNullable());
+ assertTrue(nestedMerged.getField("zip").orElseThrow().isNullable());
+ }
+
+ @Test
+ public void testMergeSchemasMakesArrayOfRecordSingleSideFieldsNullable() {
Review Comment:
An important corner case that should be tested here is where one schema is a
strict subset of the other. E.g., schemaA with x/shared, schemaB with only
shared
##########
nifi-extension-bundles/nifi-kafka-bundle/nifi-kafka-3-integration/src/test/java/org/apache/nifi/kafka/processors/ConsumeKafkaMergeSchemaIT.java:
##########
@@ -0,0 +1,310 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.nifi.kafka.processors;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import org.apache.kafka.clients.admin.AdminClient;
+import org.apache.kafka.clients.admin.AdminClientConfig;
+import org.apache.kafka.clients.admin.NewTopic;
+import org.apache.kafka.clients.producer.ProducerRecord;
+import org.apache.kafka.common.header.Header;
+import org.apache.nifi.kafka.processors.consumer.ProcessingStrategy;
+import org.apache.nifi.kafka.service.api.consumer.AutoOffsetReset;
+import org.apache.nifi.kafka.shared.attribute.KafkaFlowFileAttribute;
+import org.apache.nifi.kafka.shared.property.OutputStrategy;
+import org.apache.nifi.kafka.shared.property.SchemaConflictResolution;
+import org.apache.nifi.reporting.InitializationException;
+import org.apache.nifi.util.MockFlowFile;
+import org.apache.nifi.util.TestRunner;
+import org.apache.nifi.util.TestRunners;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.ExecutionException;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class ConsumeKafkaMergeSchemaIT extends AbstractConsumeKafkaIT {
+
+ private static final int FIRST_PARTITION = 0;
+
+ private static final String RECORD_WITH_ID = """
+ { "id": 1 }
+ """;
+
+ private static final String RECORD_WITH_NAME = """
+ { "name": "Alice" }
+ """;
+
+ private static final String INVALID_RECORD = "not-valid-json";
+
+ private TestRunner runner;
+
+ @BeforeEach
+ void setRunner() throws InitializationException {
+ runner = TestRunners.newTestRunner(ConsumeKafka.class);
+ addKafkaConnectionService(runner);
+ runner.setProperty(ConsumeKafka.CONNECTION_SERVICE,
CONNECTION_SERVICE_ID);
+ addRecordReaderService(runner);
+ addRecordWriterService(runner);
+ }
+
+ @Test
+ void testMergedSchemaProducesSingleFlowFile() throws ExecutionException,
InterruptedException, IOException {
+ final String topic = UUID.randomUUID().toString();
+ final String groupId = topic.substring(0, topic.indexOf("-"));
+
+ runner.setProperty(ConsumeKafka.GROUP_ID, groupId);
+ runner.setProperty(ConsumeKafka.TOPICS, topic);
+ runner.setProperty(ConsumeKafka.PROCESSING_STRATEGY,
ProcessingStrategy.RECORD.getValue());
+ runner.setProperty(ConsumeKafka.OUTPUT_STRATEGY,
OutputStrategy.USE_VALUE.getValue());
+ runner.setProperty(ConsumeKafka.SCHEMA_CONFLICT_RESOLUTION,
SchemaConflictResolution.CONTINUE_WITH_MERGED_SCHEMA.getValue());
+ runner.setProperty(ConsumeKafka.AUTO_OFFSET_RESET,
AutoOffsetReset.EARLIEST.getValue());
+
+ runner.run(1, false, true);
+
+ produce(topic, List.of(
+ new ProducerRecord<>(topic, FIRST_PARTITION, (String) null,
RECORD_WITH_ID, List.<Header>of()),
+ new ProducerRecord<>(topic, FIRST_PARTITION, (String) null,
RECORD_WITH_NAME, List.<Header>of())));
+
+ while
(runner.getFlowFilesForRelationship(ConsumeKafka.SUCCESS).isEmpty()) {
+ runner.run(1, false, false);
+ }
+
+ runner.run(1, true, false);
+
+ final List<MockFlowFile> successFlowFiles =
runner.getFlowFilesForRelationship(ConsumeKafka.SUCCESS);
+ assertEquals(1, successFlowFiles.size());
+
+ final MockFlowFile flowFile = successFlowFiles.getFirst();
+ flowFile.assertAttributeEquals(KafkaFlowFileAttribute.KAFKA_TOPIC,
topic);
+ flowFile.assertAttributeEquals(KafkaFlowFileAttribute.KAFKA_PARTITION,
Integer.toString(FIRST_PARTITION));
+ flowFile.assertAttributeEquals("record.count", "2");
+
+ final JsonNode jsonTree = objectMapper.readTree(flowFile.getContent());
+ final JsonNode expected = objectMapper.readTree("""
+ [
+ { "id": 1, "name": null },
+ { "id": null, "name": "Alice" }
+ ]
+ """);
+ assertEquals(expected, jsonTree);
+ }
+
+ @Test
+ void testCreateNewFlowFileDefaultProducesMultipleFlowFiles() throws
ExecutionException, InterruptedException {
+ final String topic = UUID.randomUUID().toString();
+ final String groupId = topic.substring(0, topic.indexOf("-"));
+
+ runner.setProperty(ConsumeKafka.GROUP_ID, groupId);
+ runner.setProperty(ConsumeKafka.TOPICS, topic);
+ runner.setProperty(ConsumeKafka.PROCESSING_STRATEGY,
ProcessingStrategy.RECORD.getValue());
+ runner.setProperty(ConsumeKafka.OUTPUT_STRATEGY,
OutputStrategy.USE_VALUE.getValue());
+ runner.setProperty(ConsumeKafka.AUTO_OFFSET_RESET,
AutoOffsetReset.EARLIEST.getValue());
+
+ runner.run(1, false, true);
+
+ produce(topic, List.of(
+ new ProducerRecord<>(topic, FIRST_PARTITION, (String) null,
RECORD_WITH_ID, List.<Header>of()),
+ new ProducerRecord<>(topic, FIRST_PARTITION, (String) null,
RECORD_WITH_NAME, List.<Header>of())));
+
+ while (runner.getFlowFilesForRelationship(ConsumeKafka.SUCCESS).size()
< 2) {
+ runner.run(1, false, false);
+ }
+
+ runner.run(1, true, false);
+
+ final List<MockFlowFile> successFlowFiles =
runner.getFlowFilesForRelationship(ConsumeKafka.SUCCESS);
+ assertEquals(2, successFlowFiles.size());
+
+ for (final MockFlowFile flowFile : successFlowFiles) {
+ flowFile.assertAttributeEquals(KafkaFlowFileAttribute.KAFKA_TOPIC,
topic);
+
flowFile.assertAttributeEquals(KafkaFlowFileAttribute.KAFKA_PARTITION,
Integer.toString(FIRST_PARTITION));
+ }
+ }
+
+ @Test
+ void testMergedSchemaDifferentPartitionsProduceSeparateFlowFiles() throws
Exception {
+ final String topic = UUID.randomUUID().toString();
+ final String groupId = topic.substring(0, topic.indexOf("-"));
+
+ try (final AdminClient admin = AdminClient.create(
+ Map.of(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG,
kafkaContainer.getBootstrapServers()))) {
+ admin.createTopics(List.of(new NewTopic(topic, 2, (short)
1))).all().get();
+ }
+
+ runner.setProperty(ConsumeKafka.GROUP_ID, groupId);
+ runner.setProperty(ConsumeKafka.TOPICS, topic);
+ runner.setProperty(ConsumeKafka.PROCESSING_STRATEGY,
ProcessingStrategy.RECORD.getValue());
+ runner.setProperty(ConsumeKafka.OUTPUT_STRATEGY,
OutputStrategy.USE_VALUE.getValue());
+ runner.setProperty(ConsumeKafka.SCHEMA_CONFLICT_RESOLUTION,
SchemaConflictResolution.CONTINUE_WITH_MERGED_SCHEMA.getValue());
+ runner.setProperty(ConsumeKafka.AUTO_OFFSET_RESET,
AutoOffsetReset.EARLIEST.getValue());
+
+ runner.run(1, false, true);
+
+ // Publish as one producer batch so the records are available together
for a single poll/onTrigger.
+ produce(topic, List.of(
+ new ProducerRecord<>(topic, 0, (String) null, RECORD_WITH_ID,
List.<Header>of()),
+ new ProducerRecord<>(topic, 0, (String) null,
RECORD_WITH_NAME, List.<Header>of()),
+ new ProducerRecord<>(topic, 1, (String) null,
RECORD_WITH_NAME, List.<Header>of())));
+
+ while
(totalRecordCount(runner.getFlowFilesForRelationship(ConsumeKafka.SUCCESS)) <
3) {
Review Comment:
This can potentially block forever; should fail after some time period or
number of attempts
##########
nifi-commons/nifi-record/src/test/java/org/apache/nifi/serialization/record/TestDataTypeUtils.java:
##########
@@ -1392,4 +1397,278 @@ public void
testMergeDataTypesWithManyDistinctRecordSchemasCompletesQuickly() {
assertTrue(finalSchema.getField("field_0").isPresent());
assertTrue(finalSchema.getField("field_4999").isPresent());
}
+
+ @Test
+ public void testMergeSchemasMakesSingleSideFieldsNullable() {
+ final RecordSchema schemaA = new SimpleRecordSchema(List.of(
+ new RecordField("id", RecordFieldType.STRING.getDataType(),
false)));
+ final RecordSchema schemaB = new SimpleRecordSchema(List.of(
+ new RecordField("name", RecordFieldType.STRING.getDataType(),
false)));
+
+ final RecordSchema merged = DataTypeUtils.merge(schemaA, schemaB);
+
+ assertEquals(2, merged.getFieldCount());
+ assertTrue(merged.getField("id").orElseThrow().isNullable());
+ assertTrue(merged.getField("name").orElseThrow().isNullable());
+ }
+
+ @Test
+ public void testMergeSchemasKeepsSharedNonNullableFieldNonNullable() {
+ final RecordSchema schemaA = new SimpleRecordSchema(List.of(
+ new RecordField("id", RecordFieldType.STRING.getDataType(),
false)));
+ final RecordSchema schemaB = new SimpleRecordSchema(List.of(
+ new RecordField("id", RecordFieldType.STRING.getDataType(),
false)));
+
+ final RecordSchema merged = DataTypeUtils.merge(schemaA, schemaB);
+
+ assertEquals(1, merged.getFieldCount());
+ assertFalse(merged.getField("id").orElseThrow().isNullable());
+ }
+
+ @Test
+ public void testMergeSchemasPreservesNullableWhenLeftIsNullable() {
+ final RecordSchema schemaA = new SimpleRecordSchema(List.of(
+ new RecordField("id", RecordFieldType.STRING.getDataType(),
true)));
+ final RecordSchema schemaB = new SimpleRecordSchema(List.of(
+ new RecordField("id", RecordFieldType.STRING.getDataType(),
false)));
+
+ final RecordSchema merged = DataTypeUtils.merge(schemaA, schemaB);
+
+ assertTrue(merged.getField("id").orElseThrow().isNullable());
+ }
+
+ @Test
+ public void testMergeSchemasPreservesNullableWhenRightIsNullable() {
+ final RecordSchema schemaA = new SimpleRecordSchema(List.of(
+ new RecordField("id", RecordFieldType.STRING.getDataType(),
false)));
+ final RecordSchema schemaB = new SimpleRecordSchema(List.of(
+ new RecordField("id", RecordFieldType.STRING.getDataType(),
true)));
+
+ final RecordSchema merged = DataTypeUtils.merge(schemaA, schemaB);
+
+ assertTrue(merged.getField("id").orElseThrow().isNullable());
+ }
+
+ @Test
+ public void testMergeSchemasWidensTypesAndNullifiesSingleSideFields() {
+ final RecordSchema schemaA = new SimpleRecordSchema(List.of(
+ new RecordField("id", RecordFieldType.INT.getDataType(), false),
+ new RecordField("onlyA", RecordFieldType.STRING.getDataType(),
false)));
+ final RecordSchema schemaB = new SimpleRecordSchema(List.of(
+ new RecordField("id", RecordFieldType.LONG.getDataType(), true),
+ new RecordField("onlyB", RecordFieldType.STRING.getDataType(),
Set.of("bAlias"), false)));
+
+ final RecordSchema merged = DataTypeUtils.merge(schemaA, schemaB);
+
+ assertEquals(3, merged.getFieldCount());
+ final RecordField idField = merged.getField("id").orElseThrow();
+ assertEquals(RecordFieldType.LONG,
idField.getDataType().getFieldType());
+ assertTrue(idField.isNullable());
+ assertTrue(merged.getField("onlyA").orElseThrow().isNullable());
+ assertTrue(merged.getField("onlyB").orElseThrow().isNullable());
+ }
+
+ @Test
+ public void testMergeSchemasIdenticalSchemasRetainNullability() {
+ final RecordSchema schemaA = new SimpleRecordSchema(List.of(
+ new RecordField("required", RecordFieldType.STRING.getDataType(),
false),
+ new RecordField("optional", RecordFieldType.INT.getDataType(),
true)));
+ final RecordSchema schemaB = new SimpleRecordSchema(List.of(
+ new RecordField("required", RecordFieldType.STRING.getDataType(),
false),
+ new RecordField("optional", RecordFieldType.INT.getDataType(),
true)));
+
+ final RecordSchema merged = DataTypeUtils.merge(schemaA, schemaB);
+
+ assertEquals(2, merged.getFieldCount());
+ assertFalse(merged.getField("required").orElseThrow().isNullable());
+ assertTrue(merged.getField("optional").orElseThrow().isNullable());
+ }
+
+ @Test
+ public void testMergeSchemasMakesNestedSingleSideFieldsNullable() {
+ final RecordSchema nestedA = new SimpleRecordSchema(List.of(
+ new RecordField("street", RecordFieldType.STRING.getDataType(),
false),
+ new RecordField("city", RecordFieldType.STRING.getDataType(),
false)));
+ final RecordSchema nestedB = new SimpleRecordSchema(List.of(
+ new RecordField("street", RecordFieldType.STRING.getDataType(),
false),
+ new RecordField("zip", RecordFieldType.STRING.getDataType(),
false)));
+
+ final RecordSchema schemaA = new SimpleRecordSchema(List.of(
+ new RecordField("address",
RecordFieldType.RECORD.getRecordDataType(nestedA), false)));
+ final RecordSchema schemaB = new SimpleRecordSchema(List.of(
+ new RecordField("address",
RecordFieldType.RECORD.getRecordDataType(nestedB), false)));
+
+ final RecordSchema merged = DataTypeUtils.merge(schemaA, schemaB);
+ final RecordField addressField =
merged.getField("address").orElseThrow();
+ assertFalse(addressField.isNullable());
+
+ final RecordSchema nestedMerged = ((RecordDataType)
addressField.getDataType()).getChildSchema();
+ assertEquals(3, nestedMerged.getFieldCount());
+
assertFalse(nestedMerged.getField("street").orElseThrow().isNullable());
+ assertTrue(nestedMerged.getField("city").orElseThrow().isNullable());
+ assertTrue(nestedMerged.getField("zip").orElseThrow().isNullable());
+ }
+
+ @Test
+ public void testMergeSchemasMakesArrayOfRecordSingleSideFieldsNullable() {
+ final RecordSchema elementA = new SimpleRecordSchema(List.of(
+ new RecordField("x", RecordFieldType.INT.getDataType(), false),
+ new RecordField("shared", RecordFieldType.STRING.getDataType(),
false)));
+ final RecordSchema elementB = new SimpleRecordSchema(List.of(
+ new RecordField("y", RecordFieldType.STRING.getDataType(), false),
+ new RecordField("shared", RecordFieldType.STRING.getDataType(),
false)));
+
+ final RecordSchema schemaA = new SimpleRecordSchema(List.of(
+ new RecordField("items",
RecordFieldType.ARRAY.getArrayDataType(RecordFieldType.RECORD.getRecordDataType(elementA)),
false)));
+ final RecordSchema schemaB = new SimpleRecordSchema(List.of(
+ new RecordField("items",
RecordFieldType.ARRAY.getArrayDataType(RecordFieldType.RECORD.getRecordDataType(elementB)),
false)));
+
+ final RecordSchema merged = DataTypeUtils.merge(schemaA, schemaB);
+ final RecordField itemsField = merged.getField("items").orElseThrow();
+ assertFalse(itemsField.isNullable());
+
+ final DataType elementType = ((ArrayDataType)
itemsField.getDataType()).getElementType();
+ final RecordSchema elementMerged = ((RecordDataType)
elementType).getChildSchema();
+ assertEquals(3, elementMerged.getFieldCount());
+
assertFalse(elementMerged.getField("shared").orElseThrow().isNullable());
+ assertTrue(elementMerged.getField("x").orElseThrow().isNullable());
+ assertTrue(elementMerged.getField("y").orElseThrow().isNullable());
+ }
+
+ @Test
+ public void
testMergeSchemasNullifiesTopLevelRecordFieldPresentOnOnlyOneSide() {
+ final RecordSchema nested = new SimpleRecordSchema(List.of(
+ new RecordField("value", RecordFieldType.STRING.getDataType(),
false)));
+
+ final RecordSchema schemaA = new SimpleRecordSchema(List.of(
+ new RecordField("id", RecordFieldType.STRING.getDataType(), false),
+ new RecordField("details",
RecordFieldType.RECORD.getRecordDataType(nested), false)));
+ final RecordSchema schemaB = new SimpleRecordSchema(List.of(
+ new RecordField("id", RecordFieldType.STRING.getDataType(),
false)));
+
+ final RecordSchema merged = DataTypeUtils.merge(schemaA, schemaB);
+
+ assertFalse(merged.getField("id").orElseThrow().isNullable());
+ assertTrue(merged.getField("details").orElseThrow().isNullable());
+ final RecordSchema detailsSchema = ((RecordDataType)
merged.getField("details").orElseThrow().getDataType()).getChildSchema();
+
assertFalse(detailsSchema.getField("value").orElseThrow().isNullable());
+ }
+
+ @Test
+ public void testMergeSchemasMakesDeeplyNestedSingleSideFieldsNullable() {
+ final RecordSchema leafA = new SimpleRecordSchema(List.of(
+ new RecordField("aOnly", RecordFieldType.STRING.getDataType(),
false),
+ new RecordField("common", RecordFieldType.INT.getDataType(),
false)));
+ final RecordSchema leafB = new SimpleRecordSchema(List.of(
+ new RecordField("bOnly", RecordFieldType.STRING.getDataType(),
false),
+ new RecordField("common", RecordFieldType.INT.getDataType(),
false)));
+
+ final RecordSchema midA = new SimpleRecordSchema(List.of(
+ new RecordField("leaf",
RecordFieldType.RECORD.getRecordDataType(leafA), false)));
+ final RecordSchema midB = new SimpleRecordSchema(List.of(
+ new RecordField("leaf",
RecordFieldType.RECORD.getRecordDataType(leafB), false)));
+
+ final RecordSchema schemaA = new SimpleRecordSchema(List.of(
+ new RecordField("mid",
RecordFieldType.RECORD.getRecordDataType(midA), false)));
+ final RecordSchema schemaB = new SimpleRecordSchema(List.of(
+ new RecordField("mid",
RecordFieldType.RECORD.getRecordDataType(midB), false)));
+
+ final RecordSchema merged = DataTypeUtils.merge(schemaA, schemaB);
+ final RecordSchema midMerged = ((RecordDataType)
merged.getField("mid").orElseThrow().getDataType()).getChildSchema();
+ final RecordSchema leafMerged = ((RecordDataType)
midMerged.getField("leaf").orElseThrow().getDataType()).getChildSchema();
+
+ assertFalse(leafMerged.getField("common").orElseThrow().isNullable());
+ assertTrue(leafMerged.getField("aOnly").orElseThrow().isNullable());
+ assertTrue(leafMerged.getField("bOnly").orElseThrow().isNullable());
+ }
+
+ @Test
+ public void testMergeSchemasMatchesFieldsByAliasWithoutNullifying() {
+ final RecordSchema schemaA = new SimpleRecordSchema(List.of(
+ new RecordField("id", RecordFieldType.STRING.getDataType(),
false)));
+ final RecordSchema schemaB = new SimpleRecordSchema(List.of(
+ new RecordField("id", RecordFieldType.STRING.getDataType(),
Set.of("identifier"), false)));
+
+ final RecordSchema merged = DataTypeUtils.merge(schemaA, schemaB);
+
+ assertEquals(1, merged.getFieldCount());
+ final RecordField mergedField = merged.getField("id").orElseThrow();
+ assertFalse(mergedField.isNullable());
+ assertTrue(mergedField.getAliases().contains("identifier"));
+ }
+
+ @Test
+ public void testMergeSchemasWithEmptySchemaReturnsOtherUnchanged() {
+ final RecordSchema schemaA = new SimpleRecordSchema(List.of(
+ new RecordField("id", RecordFieldType.STRING.getDataType(),
false)));
+ final RecordSchema empty = new SimpleRecordSchema(List.of());
+
+ final RecordSchema mergedWithEmptyOther = DataTypeUtils.merge(schemaA,
empty);
+ final RecordSchema mergedWithEmptyThis = DataTypeUtils.merge(empty,
schemaA);
+
+
assertFalse(mergedWithEmptyOther.getField("id").orElseThrow().isNullable());
+
assertFalse(mergedWithEmptyThis.getField("id").orElseThrow().isNullable());
Review Comment:
Given the changes being made here, this is wrong. The intent of the changes
is to ensure that the nullability of the returned schema is updated to account
for both provided schemas in `DataTypeUtils.merge`, right? So the returned
schema here should have `true` for the nullable flag because we're merging an
empty schema with a schema having a required field.
##########
nifi-extension-bundles/nifi-kafka-bundle/nifi-kafka-3-integration/src/test/java/org/apache/nifi/kafka/processors/ConsumeKafkaMergeSchemaIT.java:
##########
@@ -0,0 +1,310 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.nifi.kafka.processors;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import org.apache.kafka.clients.admin.AdminClient;
+import org.apache.kafka.clients.admin.AdminClientConfig;
+import org.apache.kafka.clients.admin.NewTopic;
+import org.apache.kafka.clients.producer.ProducerRecord;
+import org.apache.kafka.common.header.Header;
+import org.apache.nifi.kafka.processors.consumer.ProcessingStrategy;
+import org.apache.nifi.kafka.service.api.consumer.AutoOffsetReset;
+import org.apache.nifi.kafka.shared.attribute.KafkaFlowFileAttribute;
+import org.apache.nifi.kafka.shared.property.OutputStrategy;
+import org.apache.nifi.kafka.shared.property.SchemaConflictResolution;
+import org.apache.nifi.reporting.InitializationException;
+import org.apache.nifi.util.MockFlowFile;
+import org.apache.nifi.util.TestRunner;
+import org.apache.nifi.util.TestRunners;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.ExecutionException;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class ConsumeKafkaMergeSchemaIT extends AbstractConsumeKafkaIT {
+
+ private static final int FIRST_PARTITION = 0;
+
+ private static final String RECORD_WITH_ID = """
+ { "id": 1 }
+ """;
+
+ private static final String RECORD_WITH_NAME = """
+ { "name": "Alice" }
+ """;
+
+ private static final String INVALID_RECORD = "not-valid-json";
+
+ private TestRunner runner;
+
+ @BeforeEach
+ void setRunner() throws InitializationException {
+ runner = TestRunners.newTestRunner(ConsumeKafka.class);
+ addKafkaConnectionService(runner);
+ runner.setProperty(ConsumeKafka.CONNECTION_SERVICE,
CONNECTION_SERVICE_ID);
+ addRecordReaderService(runner);
+ addRecordWriterService(runner);
+ }
+
+ @Test
+ void testMergedSchemaProducesSingleFlowFile() throws ExecutionException,
InterruptedException, IOException {
+ final String topic = UUID.randomUUID().toString();
+ final String groupId = topic.substring(0, topic.indexOf("-"));
+
+ runner.setProperty(ConsumeKafka.GROUP_ID, groupId);
+ runner.setProperty(ConsumeKafka.TOPICS, topic);
+ runner.setProperty(ConsumeKafka.PROCESSING_STRATEGY,
ProcessingStrategy.RECORD.getValue());
+ runner.setProperty(ConsumeKafka.OUTPUT_STRATEGY,
OutputStrategy.USE_VALUE.getValue());
+ runner.setProperty(ConsumeKafka.SCHEMA_CONFLICT_RESOLUTION,
SchemaConflictResolution.CONTINUE_WITH_MERGED_SCHEMA.getValue());
+ runner.setProperty(ConsumeKafka.AUTO_OFFSET_RESET,
AutoOffsetReset.EARLIEST.getValue());
+
+ runner.run(1, false, true);
+
+ produce(topic, List.of(
+ new ProducerRecord<>(topic, FIRST_PARTITION, (String) null,
RECORD_WITH_ID, List.<Header>of()),
+ new ProducerRecord<>(topic, FIRST_PARTITION, (String) null,
RECORD_WITH_NAME, List.<Header>of())));
+
+ while
(runner.getFlowFilesForRelationship(ConsumeKafka.SUCCESS).isEmpty()) {
+ runner.run(1, false, false);
+ }
+
+ runner.run(1, true, false);
+
+ final List<MockFlowFile> successFlowFiles =
runner.getFlowFilesForRelationship(ConsumeKafka.SUCCESS);
+ assertEquals(1, successFlowFiles.size());
+
+ final MockFlowFile flowFile = successFlowFiles.getFirst();
+ flowFile.assertAttributeEquals(KafkaFlowFileAttribute.KAFKA_TOPIC,
topic);
+ flowFile.assertAttributeEquals(KafkaFlowFileAttribute.KAFKA_PARTITION,
Integer.toString(FIRST_PARTITION));
+ flowFile.assertAttributeEquals("record.count", "2");
+
+ final JsonNode jsonTree = objectMapper.readTree(flowFile.getContent());
+ final JsonNode expected = objectMapper.readTree("""
+ [
+ { "id": 1, "name": null },
+ { "id": null, "name": "Alice" }
+ ]
+ """);
+ assertEquals(expected, jsonTree);
+ }
+
+ @Test
+ void testCreateNewFlowFileDefaultProducesMultipleFlowFiles() throws
ExecutionException, InterruptedException {
+ final String topic = UUID.randomUUID().toString();
+ final String groupId = topic.substring(0, topic.indexOf("-"));
+
+ runner.setProperty(ConsumeKafka.GROUP_ID, groupId);
+ runner.setProperty(ConsumeKafka.TOPICS, topic);
+ runner.setProperty(ConsumeKafka.PROCESSING_STRATEGY,
ProcessingStrategy.RECORD.getValue());
+ runner.setProperty(ConsumeKafka.OUTPUT_STRATEGY,
OutputStrategy.USE_VALUE.getValue());
+ runner.setProperty(ConsumeKafka.AUTO_OFFSET_RESET,
AutoOffsetReset.EARLIEST.getValue());
+
+ runner.run(1, false, true);
+
+ produce(topic, List.of(
+ new ProducerRecord<>(topic, FIRST_PARTITION, (String) null,
RECORD_WITH_ID, List.<Header>of()),
+ new ProducerRecord<>(topic, FIRST_PARTITION, (String) null,
RECORD_WITH_NAME, List.<Header>of())));
+
+ while (runner.getFlowFilesForRelationship(ConsumeKafka.SUCCESS).size()
< 2) {
+ runner.run(1, false, false);
+ }
+
+ runner.run(1, true, false);
+
+ final List<MockFlowFile> successFlowFiles =
runner.getFlowFilesForRelationship(ConsumeKafka.SUCCESS);
+ assertEquals(2, successFlowFiles.size());
+
+ for (final MockFlowFile flowFile : successFlowFiles) {
+ flowFile.assertAttributeEquals(KafkaFlowFileAttribute.KAFKA_TOPIC,
topic);
+
flowFile.assertAttributeEquals(KafkaFlowFileAttribute.KAFKA_PARTITION,
Integer.toString(FIRST_PARTITION));
+ }
+ }
+
+ @Test
+ void testMergedSchemaDifferentPartitionsProduceSeparateFlowFiles() throws
Exception {
+ final String topic = UUID.randomUUID().toString();
+ final String groupId = topic.substring(0, topic.indexOf("-"));
+
+ try (final AdminClient admin = AdminClient.create(
+ Map.of(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG,
kafkaContainer.getBootstrapServers()))) {
+ admin.createTopics(List.of(new NewTopic(topic, 2, (short)
1))).all().get();
+ }
+
+ runner.setProperty(ConsumeKafka.GROUP_ID, groupId);
+ runner.setProperty(ConsumeKafka.TOPICS, topic);
+ runner.setProperty(ConsumeKafka.PROCESSING_STRATEGY,
ProcessingStrategy.RECORD.getValue());
+ runner.setProperty(ConsumeKafka.OUTPUT_STRATEGY,
OutputStrategy.USE_VALUE.getValue());
+ runner.setProperty(ConsumeKafka.SCHEMA_CONFLICT_RESOLUTION,
SchemaConflictResolution.CONTINUE_WITH_MERGED_SCHEMA.getValue());
+ runner.setProperty(ConsumeKafka.AUTO_OFFSET_RESET,
AutoOffsetReset.EARLIEST.getValue());
+
+ runner.run(1, false, true);
+
+ // Publish as one producer batch so the records are available together
for a single poll/onTrigger.
+ produce(topic, List.of(
+ new ProducerRecord<>(topic, 0, (String) null, RECORD_WITH_ID,
List.<Header>of()),
+ new ProducerRecord<>(topic, 0, (String) null,
RECORD_WITH_NAME, List.<Header>of()),
+ new ProducerRecord<>(topic, 1, (String) null,
RECORD_WITH_NAME, List.<Header>of())));
+
+ while
(totalRecordCount(runner.getFlowFilesForRelationship(ConsumeKafka.SUCCESS)) <
3) {
+ runner.run(1, false, false);
+ }
+
+ runner.run(1, true, false);
+
+ final List<MockFlowFile> successFlowFiles =
runner.getFlowFilesForRelationship(ConsumeKafka.SUCCESS);
+ assertEquals(3, totalRecordCount(successFlowFiles));
+
+ final List<MockFlowFile> partitionZero = successFlowFiles.stream()
+ .filter(ff ->
"0".equals(ff.getAttribute(KafkaFlowFileAttribute.KAFKA_PARTITION)))
+ .toList();
+ final List<MockFlowFile> partitionOne = successFlowFiles.stream()
+ .filter(ff ->
"1".equals(ff.getAttribute(KafkaFlowFileAttribute.KAFKA_PARTITION)))
+ .toList();
+
+ assertEquals(1, partitionZero.size());
+ assertEquals(1, partitionOne.size());
+ assertEquals(2, totalRecordCount(partitionZero));
+ assertEquals(1, totalRecordCount(partitionOne));
+ // Records from different partitions never share a FlowFile.
+ assertTrue(partitionZero.stream().noneMatch(ff ->
"1".equals(ff.getAttribute(KafkaFlowFileAttribute.KAFKA_PARTITION))));
+ }
+
+ private static int totalRecordCount(final List<MockFlowFile> flowFiles) {
+ return flowFiles.stream()
+ .mapToInt(ff ->
Integer.parseInt(ff.getAttribute("record.count")))
+ .sum();
+ }
+
+ @Test
+ void testMergedSchemaWithParseFailure() throws ExecutionException,
InterruptedException, IOException {
+ final String topic = UUID.randomUUID().toString();
+ final String groupId = topic.substring(0, topic.indexOf("-"));
+
+ runner.setProperty(ConsumeKafka.GROUP_ID, groupId);
+ runner.setProperty(ConsumeKafka.TOPICS, topic);
+ runner.setProperty(ConsumeKafka.PROCESSING_STRATEGY,
ProcessingStrategy.RECORD.getValue());
+ runner.setProperty(ConsumeKafka.OUTPUT_STRATEGY,
OutputStrategy.USE_VALUE.getValue());
+ runner.setProperty(ConsumeKafka.SCHEMA_CONFLICT_RESOLUTION,
SchemaConflictResolution.CONTINUE_WITH_MERGED_SCHEMA.getValue());
+ runner.setProperty(ConsumeKafka.AUTO_OFFSET_RESET,
AutoOffsetReset.EARLIEST.getValue());
+
+ runner.run(1, false, true);
+
+ produce(topic, List.of(
+ new ProducerRecord<>(topic, FIRST_PARTITION, (String) null,
RECORD_WITH_ID, List.<Header>of()),
+ new ProducerRecord<>(topic, FIRST_PARTITION, (String) null,
INVALID_RECORD, List.<Header>of()),
+ new ProducerRecord<>(topic, FIRST_PARTITION, (String) null,
RECORD_WITH_NAME, List.<Header>of())));
+
+ while
(runner.getFlowFilesForRelationship(ConsumeKafka.SUCCESS).isEmpty()) {
+ runner.run(1, false, false);
+ }
+
+ runner.run(1, true, false);
+
+ final List<MockFlowFile> successFlowFiles =
runner.getFlowFilesForRelationship(ConsumeKafka.SUCCESS);
+ assertEquals(1, successFlowFiles.size());
+
+ final MockFlowFile successFlowFile = successFlowFiles.getFirst();
+ final JsonNode jsonTree =
objectMapper.readTree(successFlowFile.getContent());
+ assertInstanceOf(ArrayNode.class, jsonTree);
+ assertEquals(2, jsonTree.size());
+
+ final List<MockFlowFile> parseFailureFlowFiles =
runner.getFlowFilesForRelationship(ConsumeKafka.PARSE_FAILURE);
+ assertEquals(1, parseFailureFlowFiles.size());
+ parseFailureFlowFiles.getFirst().assertContentEquals(INVALID_RECORD);
+ }
+
+ @Test
+ void testMergedSchemaWithInjectOffset() throws Exception {
+ final MockFlowFile flowFile =
runMergedSchemaWithOutputStrategy(OutputStrategy.INJECT_OFFSET);
+ flowFile.assertAttributeEquals("record.count", "2");
+
+ final JsonNode jsonTree = objectMapper.readTree(flowFile.getContent());
+ assertInstanceOf(ArrayNode.class, jsonTree);
+ assertEquals(2, jsonTree.size());
+ assertEquals(1, jsonTree.get(0).get("id").asInt());
+ assertTrue(jsonTree.get(0).has("kafkaOffset"));
+ assertEquals("Alice", jsonTree.get(1).get("name").asText());
+ assertTrue(jsonTree.get(1).has("kafkaOffset"));
+ }
+
+ @Test
+ void testMergedSchemaWithUseWrapper() throws Exception {
+ final MockFlowFile flowFile =
runMergedSchemaWithOutputStrategy(OutputStrategy.USE_WRAPPER);
+ flowFile.assertAttributeEquals("record.count", "2");
+
+ final JsonNode jsonTree = objectMapper.readTree(flowFile.getContent());
+ assertInstanceOf(ArrayNode.class, jsonTree);
+ assertEquals(2, jsonTree.size());
+ assertEquals(1, jsonTree.get(0).get("value").get("id").asInt());
+ assertTrue(jsonTree.get(0).has("metadata"));
+ assertEquals("Alice",
jsonTree.get(1).get("value").get("name").asText());
+ assertTrue(jsonTree.get(1).has("metadata"));
+ }
+
+ @Test
+ void testMergedSchemaWithInjectMetadata() throws Exception {
+ final MockFlowFile flowFile =
runMergedSchemaWithOutputStrategy(OutputStrategy.INJECT_METADATA);
+ flowFile.assertAttributeEquals("record.count", "2");
+
+ final JsonNode jsonTree = objectMapper.readTree(flowFile.getContent());
+ assertInstanceOf(ArrayNode.class, jsonTree);
+ assertEquals(2, jsonTree.size());
+ assertEquals(1, jsonTree.get(0).get("id").asInt());
+ assertTrue(jsonTree.get(0).has("kafkaMetadata"));
+ assertEquals("Alice", jsonTree.get(1).get("name").asText());
+ assertTrue(jsonTree.get(1).has("kafkaMetadata"));
+ }
+
+ private MockFlowFile runMergedSchemaWithOutputStrategy(final
OutputStrategy outputStrategy)
+ throws ExecutionException, InterruptedException {
+ final String topic = UUID.randomUUID().toString();
+ final String groupId = topic.substring(0, topic.indexOf("-"));
+
+ runner.setProperty(ConsumeKafka.GROUP_ID, groupId);
+ runner.setProperty(ConsumeKafka.TOPICS, topic);
+ runner.setProperty(ConsumeKafka.PROCESSING_STRATEGY,
ProcessingStrategy.RECORD.getValue());
+ runner.setProperty(ConsumeKafka.OUTPUT_STRATEGY,
outputStrategy.getValue());
+ runner.setProperty(ConsumeKafka.SCHEMA_CONFLICT_RESOLUTION,
SchemaConflictResolution.CONTINUE_WITH_MERGED_SCHEMA.getValue());
+ runner.setProperty(ConsumeKafka.AUTO_OFFSET_RESET,
AutoOffsetReset.EARLIEST.getValue());
+
+ runner.run(1, false, true);
+
+ produce(topic, List.of(
+ new ProducerRecord<>(topic, FIRST_PARTITION, (String) null,
RECORD_WITH_ID, List.<Header>of()),
+ new ProducerRecord<>(topic, FIRST_PARTITION, (String) null,
RECORD_WITH_NAME, List.<Header>of())));
+
+ while
(runner.getFlowFilesForRelationship(ConsumeKafka.SUCCESS).isEmpty()) {
Review Comment:
This can potentially block forever; should fail after some time period or
number of attempts
--
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: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]