gemini-code-assist[bot] commented on code in PR #38362: URL: https://github.com/apache/beam/pull/38362#discussion_r3178116943
########## sdks/java/io/datadog/src/main/java/org/apache/beam/sdk/io/datadog/DatadogWriteSchemaTransformProvider.java: ########## @@ -0,0 +1,311 @@ +/* + * 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.beam.sdk.io.datadog; + +import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkNotNull; + +import com.google.api.client.http.HttpResponse; +import com.google.auto.service.AutoService; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; +import org.apache.beam.sdk.coders.KvCoder; +import org.apache.beam.sdk.coders.RowCoder; +import org.apache.beam.sdk.coders.VarIntCoder; +import org.apache.beam.sdk.schemas.Schema; +import org.apache.beam.sdk.schemas.transforms.SchemaTransform; +import org.apache.beam.sdk.schemas.transforms.SchemaTransformProvider; +import org.apache.beam.sdk.schemas.transforms.TypedSchemaTransformProvider; +import org.apache.beam.sdk.schemas.transforms.providers.ErrorHandling; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.transforms.ParDo; +import org.apache.beam.sdk.values.KV; +import org.apache.beam.sdk.values.PCollection; +import org.apache.beam.sdk.values.PCollectionRowTuple; +import org.apache.beam.sdk.values.PCollectionTuple; +import org.apache.beam.sdk.values.Row; +import org.apache.beam.sdk.values.TupleTag; +import org.apache.beam.sdk.values.TupleTagList; +import org.checkerframework.checker.nullness.qual.Nullable; + +@AutoService(SchemaTransformProvider.class) +public class DatadogWriteSchemaTransformProvider + extends TypedSchemaTransformProvider<DatadogWriteSchemaTransformConfiguration> { + private static final String IDENTIFIER = "beam:schematransform:org.apache.beam:datadog_write:v1"; + static final String INPUT = "input"; + static final String OUTPUT = "output"; + static final String ERROR = "errors"; + public static final TupleTag<Row> ERROR_TAG = new TupleTag<Row>() {}; + public static final TupleTag<Void> OUTPUT_TAG = new TupleTag<Void>() {}; + + @Override + protected Class<DatadogWriteSchemaTransformConfiguration> configurationClass() { + return DatadogWriteSchemaTransformConfiguration.class; + } + + /** Returns the expected {@link SchemaTransform} of the configuration. */ + @Override + protected SchemaTransform from(DatadogWriteSchemaTransformConfiguration configuration) { + return new DatadogWriteSchemaTransform(configuration); + } + + /** Implementation of the {@link TypedSchemaTransformProvider} identifier method. */ + @Override + public String identifier() { + return IDENTIFIER; + } + + /** Implementation of the {@link TypedSchemaTransformProvider} input collection names method. */ + @Override + public List<String> inputCollectionNames() { + return Collections.singletonList(INPUT); + } + + /** Implementation of the {@link TypedSchemaTransformProvider} output collection names method. */ + @Override + public List<String> outputCollectionNames() { + return Arrays.asList(OUTPUT, ERROR); + } + + /** + * An implementation of {@link SchemaTransform} for Datadog Write jobs configured using {@link + * DatadogWriteSchemaTransformConfiguration}. + */ + static class DatadogWriteSchemaTransform extends SchemaTransform { + private final DatadogWriteSchemaTransformConfiguration configuration; + + DatadogWriteSchemaTransform(DatadogWriteSchemaTransformConfiguration configuration) { + this.configuration = configuration; + } + + @Override + public PCollectionRowTuple expand(PCollectionRowTuple input) { + // Validate configuration parameters + configuration.validate(); + + // Obtain input rows + PCollection<Row> inputRows = input.get(INPUT); + + // Obtain input schema + Schema inputSchema = inputRows.getSchema(); + + // Create error schema based on input schema + Schema errorSchema = ErrorHandling.errorSchema(inputSchema); + + // Check for errors + boolean handleErrors = ErrorHandling.hasOutput(configuration.getErrorHandling()); + + Integer parallelism = configuration.getParallelism(); + int calculatedParallelism = parallelism != null ? parallelism : 1; + + // Inject Keys directly wrapping raw input rows + PCollection<KV<Integer, Row>> keyedEvents = + inputRows + .apply("InjectKeys", ParDo.of(new CreateRowKeysFn(calculatedParallelism))) + .setCoder(KvCoder.of(VarIntCoder.of(), RowCoder.of(inputSchema))); + + // Apply the write transform directly. All errors flow to Side Output. + PCollectionTuple resultTuple = + keyedEvents.apply( + "WriteToDatadog", + ParDo.of( + new RowBasedDatadogEventWriter( + configuration.getUrl(), + configuration.getApiKey(), + errorSchema, + handleErrors)) Review Comment:  The current implementation of `RowBasedDatadogEventWriter` ignores the batching configuration parameters (`batchCount`, `minBatchCount`, `maxBufferSize`) and sends a separate HTTP request for every single row (see line 270). This is highly inefficient and may lead to hitting Datadog API rate limits. You should implement batching logic, for example by using `GroupIntoBatches` before the write transform or by leveraging `DatadogIO` if it supports batched writes. ########## sdks/java/io/datadog/src/main/java/org/apache/beam/sdk/io/datadog/DatadogWriteSchemaTransformProvider.java: ########## @@ -0,0 +1,311 @@ +/* + * 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.beam.sdk.io.datadog; + +import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkNotNull; + +import com.google.api.client.http.HttpResponse; +import com.google.auto.service.AutoService; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; +import org.apache.beam.sdk.coders.KvCoder; +import org.apache.beam.sdk.coders.RowCoder; +import org.apache.beam.sdk.coders.VarIntCoder; +import org.apache.beam.sdk.schemas.Schema; +import org.apache.beam.sdk.schemas.transforms.SchemaTransform; +import org.apache.beam.sdk.schemas.transforms.SchemaTransformProvider; +import org.apache.beam.sdk.schemas.transforms.TypedSchemaTransformProvider; +import org.apache.beam.sdk.schemas.transforms.providers.ErrorHandling; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.transforms.ParDo; +import org.apache.beam.sdk.values.KV; +import org.apache.beam.sdk.values.PCollection; +import org.apache.beam.sdk.values.PCollectionRowTuple; +import org.apache.beam.sdk.values.PCollectionTuple; +import org.apache.beam.sdk.values.Row; +import org.apache.beam.sdk.values.TupleTag; +import org.apache.beam.sdk.values.TupleTagList; +import org.checkerframework.checker.nullness.qual.Nullable; + +@AutoService(SchemaTransformProvider.class) +public class DatadogWriteSchemaTransformProvider + extends TypedSchemaTransformProvider<DatadogWriteSchemaTransformConfiguration> { + private static final String IDENTIFIER = "beam:schematransform:org.apache.beam:datadog_write:v1"; + static final String INPUT = "input"; + static final String OUTPUT = "output"; + static final String ERROR = "errors"; + public static final TupleTag<Row> ERROR_TAG = new TupleTag<Row>() {}; + public static final TupleTag<Void> OUTPUT_TAG = new TupleTag<Void>() {}; + + @Override + protected Class<DatadogWriteSchemaTransformConfiguration> configurationClass() { + return DatadogWriteSchemaTransformConfiguration.class; + } + + /** Returns the expected {@link SchemaTransform} of the configuration. */ + @Override + protected SchemaTransform from(DatadogWriteSchemaTransformConfiguration configuration) { + return new DatadogWriteSchemaTransform(configuration); + } + + /** Implementation of the {@link TypedSchemaTransformProvider} identifier method. */ + @Override + public String identifier() { + return IDENTIFIER; + } + + /** Implementation of the {@link TypedSchemaTransformProvider} input collection names method. */ + @Override + public List<String> inputCollectionNames() { + return Collections.singletonList(INPUT); + } + + /** Implementation of the {@link TypedSchemaTransformProvider} output collection names method. */ + @Override + public List<String> outputCollectionNames() { + return Arrays.asList(OUTPUT, ERROR); + } + + /** + * An implementation of {@link SchemaTransform} for Datadog Write jobs configured using {@link + * DatadogWriteSchemaTransformConfiguration}. + */ + static class DatadogWriteSchemaTransform extends SchemaTransform { + private final DatadogWriteSchemaTransformConfiguration configuration; + + DatadogWriteSchemaTransform(DatadogWriteSchemaTransformConfiguration configuration) { + this.configuration = configuration; + } + + @Override + public PCollectionRowTuple expand(PCollectionRowTuple input) { + // Validate configuration parameters + configuration.validate(); + + // Obtain input rows + PCollection<Row> inputRows = input.get(INPUT); + + // Obtain input schema + Schema inputSchema = inputRows.getSchema(); + + // Create error schema based on input schema + Schema errorSchema = ErrorHandling.errorSchema(inputSchema); + + // Check for errors + boolean handleErrors = ErrorHandling.hasOutput(configuration.getErrorHandling()); + + Integer parallelism = configuration.getParallelism(); + int calculatedParallelism = parallelism != null ? parallelism : 1; + + // Inject Keys directly wrapping raw input rows + PCollection<KV<Integer, Row>> keyedEvents = + inputRows + .apply("InjectKeys", ParDo.of(new CreateRowKeysFn(calculatedParallelism))) + .setCoder(KvCoder.of(VarIntCoder.of(), RowCoder.of(inputSchema))); + + // Apply the write transform directly. All errors flow to Side Output. + PCollectionTuple resultTuple = + keyedEvents.apply( + "WriteToDatadog", + ParDo.of( + new RowBasedDatadogEventWriter( + configuration.getUrl(), + configuration.getApiKey(), + errorSchema, + handleErrors)) + .withOutputTags(OUTPUT_TAG, TupleTagList.of(ERROR_TAG))); + + // Obtain the single unified error output stream + PCollection<Row> errorOutput = resultTuple.get(ERROR_TAG).setRowSchema(errorSchema); + + // Return the unified errors stream if error handling is active + ErrorHandling errorHandling = configuration.getErrorHandling(); + if (errorHandling != null) { + return PCollectionRowTuple.of(errorHandling.getOutput(), errorOutput); + } else { + return PCollectionRowTuple.empty(input.getPipeline()); + } Review Comment:  The returned `PCollectionRowTuple` should contain the collections defined in `outputCollectionNames()` (i.e., `output` and `errors`). Currently, it returns an empty tuple if `errorHandling` is null, or a tuple with a potentially custom-named error collection if it is not null. This inconsistency can cause issues for downstream transforms or YAML pipelines expecting the standard output names. ########## sdks/java/io/datadog/src/main/java/org/apache/beam/sdk/io/datadog/DatadogWriteSchemaTransformProvider.java: ########## @@ -0,0 +1,311 @@ +/* + * 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.beam.sdk.io.datadog; + +import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkNotNull; + +import com.google.api.client.http.HttpResponse; +import com.google.auto.service.AutoService; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; +import org.apache.beam.sdk.coders.KvCoder; +import org.apache.beam.sdk.coders.RowCoder; +import org.apache.beam.sdk.coders.VarIntCoder; +import org.apache.beam.sdk.schemas.Schema; +import org.apache.beam.sdk.schemas.transforms.SchemaTransform; +import org.apache.beam.sdk.schemas.transforms.SchemaTransformProvider; +import org.apache.beam.sdk.schemas.transforms.TypedSchemaTransformProvider; +import org.apache.beam.sdk.schemas.transforms.providers.ErrorHandling; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.transforms.ParDo; +import org.apache.beam.sdk.values.KV; +import org.apache.beam.sdk.values.PCollection; +import org.apache.beam.sdk.values.PCollectionRowTuple; +import org.apache.beam.sdk.values.PCollectionTuple; +import org.apache.beam.sdk.values.Row; +import org.apache.beam.sdk.values.TupleTag; +import org.apache.beam.sdk.values.TupleTagList; +import org.checkerframework.checker.nullness.qual.Nullable; + +@AutoService(SchemaTransformProvider.class) +public class DatadogWriteSchemaTransformProvider + extends TypedSchemaTransformProvider<DatadogWriteSchemaTransformConfiguration> { + private static final String IDENTIFIER = "beam:schematransform:org.apache.beam:datadog_write:v1"; + static final String INPUT = "input"; + static final String OUTPUT = "output"; + static final String ERROR = "errors"; + public static final TupleTag<Row> ERROR_TAG = new TupleTag<Row>() {}; + public static final TupleTag<Void> OUTPUT_TAG = new TupleTag<Void>() {}; + + @Override + protected Class<DatadogWriteSchemaTransformConfiguration> configurationClass() { + return DatadogWriteSchemaTransformConfiguration.class; + } + + /** Returns the expected {@link SchemaTransform} of the configuration. */ + @Override + protected SchemaTransform from(DatadogWriteSchemaTransformConfiguration configuration) { + return new DatadogWriteSchemaTransform(configuration); + } + + /** Implementation of the {@link TypedSchemaTransformProvider} identifier method. */ + @Override + public String identifier() { + return IDENTIFIER; + } + + /** Implementation of the {@link TypedSchemaTransformProvider} input collection names method. */ + @Override + public List<String> inputCollectionNames() { + return Collections.singletonList(INPUT); + } + + /** Implementation of the {@link TypedSchemaTransformProvider} output collection names method. */ + @Override + public List<String> outputCollectionNames() { + return Arrays.asList(OUTPUT, ERROR); + } + + /** + * An implementation of {@link SchemaTransform} for Datadog Write jobs configured using {@link + * DatadogWriteSchemaTransformConfiguration}. + */ + static class DatadogWriteSchemaTransform extends SchemaTransform { + private final DatadogWriteSchemaTransformConfiguration configuration; + + DatadogWriteSchemaTransform(DatadogWriteSchemaTransformConfiguration configuration) { + this.configuration = configuration; + } + + @Override + public PCollectionRowTuple expand(PCollectionRowTuple input) { + // Validate configuration parameters + configuration.validate(); + + // Obtain input rows + PCollection<Row> inputRows = input.get(INPUT); + + // Obtain input schema + Schema inputSchema = inputRows.getSchema(); + + // Create error schema based on input schema + Schema errorSchema = ErrorHandling.errorSchema(inputSchema); + + // Check for errors + boolean handleErrors = ErrorHandling.hasOutput(configuration.getErrorHandling()); + + Integer parallelism = configuration.getParallelism(); + int calculatedParallelism = parallelism != null ? parallelism : 1; + + // Inject Keys directly wrapping raw input rows + PCollection<KV<Integer, Row>> keyedEvents = + inputRows + .apply("InjectKeys", ParDo.of(new CreateRowKeysFn(calculatedParallelism))) + .setCoder(KvCoder.of(VarIntCoder.of(), RowCoder.of(inputSchema))); Review Comment:  The `parallelism` parameter is used to assign keys to rows, but since `InjectKeys` and `WriteToDatadog` are adjacent `ParDo` transforms, they will likely be fused by the runner. Without an explicit shuffle (e.g., via `Reshuffle` or `GroupIntoBatches`), this setting will not effectively control the number of concurrent writers. ########## sdks/java/io/datadog/src/test/java/org/apache/beam/sdk/io/datadog/DatadogWriteSchemaTransformProviderTest.java: ########## @@ -0,0 +1,566 @@ +/* + * 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.beam.sdk.io.datadog; + +import static org.apache.beam.sdk.io.datadog.DatadogWriteSchemaTransformProvider.ERROR; +import static org.apache.beam.sdk.io.datadog.DatadogWriteSchemaTransformProvider.INPUT; +import static org.apache.beam.sdk.io.datadog.DatadogWriteSchemaTransformProvider.OUTPUT; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.Arrays; +import java.util.List; +import java.util.ServiceLoader; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; +import org.apache.beam.sdk.Pipeline.PipelineExecutionException; +import org.apache.beam.sdk.schemas.AutoValueSchema; +import org.apache.beam.sdk.schemas.NoSuchSchemaException; +import org.apache.beam.sdk.schemas.Schema; +import org.apache.beam.sdk.schemas.SchemaRegistry; +import org.apache.beam.sdk.schemas.transforms.SchemaTransform; +import org.apache.beam.sdk.schemas.transforms.SchemaTransformProvider; +import org.apache.beam.sdk.schemas.transforms.providers.ErrorHandling; +import org.apache.beam.sdk.testing.PAssert; +import org.apache.beam.sdk.testing.TestPipeline; +import org.apache.beam.sdk.transforms.Create; +import org.apache.beam.sdk.values.PCollection; +import org.apache.beam.sdk.values.PCollectionRowTuple; +import org.apache.beam.sdk.values.Row; +import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Lists; +import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Sets; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@RunWith(JUnit4.class) +public class DatadogWriteSchemaTransformProviderTest { + + private static final Logger LOG = + LoggerFactory.getLogger(DatadogWriteSchemaTransformProviderTest.class); + + @Rule public TestPipeline p = TestPipeline.create(); + + private static final Schema SCHEMA = + Schema.builder() + .addStringField("ddsource") + .addNullableField("ddtags", Schema.FieldType.STRING) + .addStringField("hostname") + .addNullableField("service", Schema.FieldType.STRING) + .addStringField("message") + .build(); + + private static final List<Row> ROWS = + Arrays.asList( + Row.withSchema(SCHEMA) + .withFieldValue("ddsource", "my-source") + .withFieldValue("ddtags", "tag1:value1,tag2") + .withFieldValue("hostname", "my-host") + .withFieldValue("service", "my-service") + .withFieldValue("message", "Hello World 1") + .build(), + Row.withSchema(SCHEMA) + .withFieldValue("ddsource", "my-source-2") + .withFieldValue("ddtags", null) + .withFieldValue("hostname", "my-host-2") + .withFieldValue("service", null) + .withFieldValue("message", "Hello World 2") + .build()); + + private List<DatadogEvent> events; + + @org.junit.Before + public void setUp() { + events = + Arrays.asList( + DatadogEvent.newBuilder() + .withSource("my-source") + .withTags("tag1:value1,tag2") + .withHostname("my-host") + .withService("my-service") + .withMessage("Hello World 1") + .build(), + DatadogEvent.newBuilder() + .withSource("my-source-2") + .withHostname("my-host-2") + .withMessage("Hello World 2") + .build()); + } + + @Test + public void testWriteInvalidConfigurations() { + + // apiKey not set + assertThrows( + IllegalStateException.class, + () -> { + DatadogWriteSchemaTransformConfiguration.builder() + .setUrl("http://localhost:8080") + // .setApiKey("test-api-key") # ApiKey is mandatory + .build() + .validate(); + }); + + // url not set + assertThrows( + IllegalStateException.class, + () -> { + DatadogWriteSchemaTransformConfiguration.builder() + // .setUrl("http://localhost:8080") # Url is mandatory + .setApiKey("test-api-key") + .build() + .validate(); + }); + } + + @Test + public void testWriteBuildTransform() { + DatadogWriteSchemaTransformProvider provider = new DatadogWriteSchemaTransformProvider(); + DatadogWriteSchemaTransformConfiguration configuration = + DatadogWriteSchemaTransformConfiguration.builder() + .setApiKey("test-api-key") + .setUrl("http://localhost:8080") + .build(); + + provider.from(configuration); + } + + @Test + public void testWriteBuildTransformAndRun() { + DatadogWriteSchemaTransformProvider provider = new DatadogWriteSchemaTransformProvider(); + DatadogWriteSchemaTransformConfiguration configuration = + DatadogWriteSchemaTransformConfiguration.builder() + .setApiKey("test-api-key") + .setUrl("http://localhost:8080") + .build(); + + SchemaTransform transform = provider.from(configuration); + + PCollection<Row> input = p.apply("Create", Create.of(ROWS).withRowSchema(SCHEMA)); + PCollectionRowTuple inputTuple = PCollectionRowTuple.of(INPUT, input); + PCollectionRowTuple output = transform.expand(inputTuple); + assertTrue(output.getAll().isEmpty()); + + try { + p.run().waitUntilFinish(); + fail("Expected a PipelineExecutionException due to connection refusal."); + } catch (PipelineExecutionException e) { + Throwable cause = e.getCause(); + while (cause.getCause() != null) { + cause = cause.getCause(); + } + assertTrue( + "Expected cause to be java.net.ConnectException", + cause instanceof java.net.ConnectException); + } + } + + @Test + public void testWriteBuildTransformWithCorrectFields() { + ServiceLoader<SchemaTransformProvider> serviceLoader = + ServiceLoader.load(SchemaTransformProvider.class); + List<SchemaTransformProvider> providers = + StreamSupport.stream(serviceLoader.spliterator(), false) + .filter(provider -> provider.getClass() == DatadogWriteSchemaTransformProvider.class) + .collect(Collectors.toList()); + SchemaTransformProvider datadogProvider = providers.get(0); + assertEquals(datadogProvider.outputCollectionNames(), Lists.newArrayList(OUTPUT, ERROR)); + + assertEquals( + Sets.newHashSet( + "url", + "api_key", + "min_batch_count", + "batch_count", + "max_buffer_size", + "parallelism", + "error_handling"), + datadogProvider.configurationSchema().getFields().stream() + .map(field -> field.getName()) + .collect(Collectors.toSet())); + } + + @Test + public void testRowToDatadogEvent() { + for (int i = 0; i < ROWS.size(); i++) { + DatadogEvent actual = DatadogWriteSchemaTransformProvider.rowToEvent(ROWS.get(i)); + assertEquals(events.get(i), actual); + } + } + + @Test + public void testRowToDatadogEventWithMissingOptionalFields() { + Schema missingFieldsSchema = + Schema.builder() + .addStringField("ddsource") + .addStringField("hostname") + .addStringField("message") + .build(); + + Row row = + Row.withSchema(missingFieldsSchema) + .withFieldValue("ddsource", "my-source") + .withFieldValue("hostname", "my-host") + .withFieldValue("message", "Hello World 1") + .build(); + + DatadogEvent expectedEvent = + DatadogEvent.newBuilder() + .withSource("my-source") + .withHostname("my-host") + .withMessage("Hello World 1") + .build(); + + DatadogEvent actual = DatadogWriteSchemaTransformProvider.rowToEvent(row); + assertEquals(expectedEvent, actual); + } + + @Test + public void testRowToDatadogEventWithExtraFields_DiscardsExtraFields() { + Schema extraFieldsSchema = + Schema.builder() + .addStringField("ddsource") + .addNullableField("ddtags", Schema.FieldType.STRING) + .addStringField("hostname") + .addNullableField("service", Schema.FieldType.STRING) + .addStringField("message") + .addStringField("extra_field") + .build(); + + Row row = + Row.withSchema(extraFieldsSchema) + .withFieldValue("ddsource", "my-source") + .withFieldValue("ddtags", "tag1:value1,tag2") + .withFieldValue("hostname", "my-host") + .withFieldValue("service", "my-service") + .withFieldValue("message", "Hello World 1") + .withFieldValue("extra_field", "extra_value") + .build(); + + DatadogEvent expectedEvent = + DatadogEvent.newBuilder() + .withSource("my-source") + .withTags("tag1:value1,tag2") + .withHostname("my-host") + .withService("my-service") + .withMessage("Hello World 1") + .build(); + + DatadogEvent actual = DatadogWriteSchemaTransformProvider.rowToEvent(row); + assertEquals(expectedEvent, actual); + } + + @Test(expected = NullPointerException.class) + public void testRowToDatadogEventWithNullRequiredField() { + Schema nullSchema = + Schema.builder() + .addStringField("ddsource") + .addNullableField("ddtags", Schema.FieldType.STRING) + .addStringField("hostname") + .addNullableField("service", Schema.FieldType.STRING) + .addNullableField("message", Schema.FieldType.STRING) + .build(); + + Row row = + Row.withSchema(nullSchema) + .withFieldValue("ddsource", "my-source") + .withFieldValue("ddtags", "tag1:value1,tag2") + .withFieldValue("hostname", "my-host") + .withFieldValue("service", "my-service") + .withFieldValue("message", null) + .build(); + + DatadogWriteSchemaTransformProvider.rowToEvent(row); + } + + @Test + public void testBuildTransformWithAllParameters() { + DatadogWriteSchemaTransformProvider provider = new DatadogWriteSchemaTransformProvider(); + DatadogWriteSchemaTransformConfiguration configuration = + DatadogWriteSchemaTransformConfiguration.builder() + .setApiKey("test-api-key") + .setUrl("http://localhost:8080") + .setBatchCount(10) + .setMaxBufferSize(100L) + .setParallelism(2) + .build(); + + SchemaTransform transform = provider.from(configuration); + + PCollection<Row> input = p.apply("Create", Create.of(ROWS).withRowSchema(SCHEMA)); + PCollectionRowTuple inputTuple = PCollectionRowTuple.of(INPUT, input); + PCollectionRowTuple output = transform.expand(inputTuple); + assertTrue(output.getAll().isEmpty()); + + try { + p.run().waitUntilFinish(); + fail("Expected a PipelineExecutionException due to connection refusal."); + } catch (PipelineExecutionException e) { + Throwable cause = e.getCause(); + while (cause.getCause() != null) { + cause = cause.getCause(); + } + assertTrue( + "Expected cause to be java.net.ConnectException", + cause instanceof java.net.ConnectException); + } + } + + @Test(expected = IllegalStateException.class) + public void testBuildTransformMissingUrl() { + DatadogWriteSchemaTransformProvider provider = new DatadogWriteSchemaTransformProvider(); + provider.from( + DatadogWriteSchemaTransformConfiguration.builder().setApiKey("test-api-key").build()); + } + + @Test(expected = IllegalStateException.class) + public void testBuildTransformMissingApiKey() { + DatadogWriteSchemaTransformProvider provider = new DatadogWriteSchemaTransformProvider(); + provider.from(DatadogWriteSchemaTransformConfiguration.builder().setUrl("test-url").build()); + } + + @Test + public void testBuildTransformWithInvalidParallelism() { + DatadogWriteSchemaTransformProvider provider = new DatadogWriteSchemaTransformProvider(); + DatadogWriteSchemaTransformConfiguration configuration = + DatadogWriteSchemaTransformConfiguration.builder() + .setApiKey("test-api-key") + .setUrl("http://localhost:8080") + .setParallelism(0) + .build(); + + SchemaTransform transform = provider.from(configuration); + + PCollection<Row> input = p.apply("Create", Create.of(ROWS).withRowSchema(SCHEMA)); + PCollectionRowTuple inputTuple = PCollectionRowTuple.of(INPUT, input); + PCollectionRowTuple output = transform.expand(inputTuple); + assertTrue(output.getAll().isEmpty()); + + try { + p.run().waitUntilFinish(); + fail("Expected a PipelineExecutionException to be thrown."); + } catch (PipelineExecutionException e) { + Throwable cause = e.getCause(); + while (cause.getCause() != null) { + cause = cause.getCause(); + } + assertTrue( + "Expected cause to be of type IllegalArgumentException", + cause instanceof IllegalArgumentException); + assertTrue( + "Expected message to contain 'bound must be positive'", + cause.getMessage().contains("bound must be positive")); + } + } + + @Test + public void testBuildTransformWithInvalidBatchCount() { + DatadogWriteSchemaTransformConfiguration.builder() + .setApiKey("test-api-key") + .setUrl("http://localhost:8080") + .setBatchCount(0) + .setMinBatchCount(1) + .build() + .validate(); + } Review Comment:  This test case currently passes even when `batchCount` is `0` because there is no validation logic for this field in the configuration class, and the test lacks an assertion for failure. It should be updated to assert that an `IllegalArgumentException` is thrown once the validation is implemented. ```java @Test public void testBuildTransformWithInvalidBatchCount() { assertThrows( IllegalArgumentException.class, () -> { DatadogWriteSchemaTransformConfiguration.builder() .setApiKey("test-api-key") .setUrl("http://localhost:8080") .setBatchCount(0) .build() .validate(); }); } ``` ########## sdks/java/io/datadog/src/main/java/org/apache/beam/sdk/io/datadog/DatadogWriteSchemaTransformConfiguration.java: ########## @@ -0,0 +1,95 @@ +/* + * 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.beam.sdk.io.datadog; + +import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkArgument; + +import com.google.auto.value.AutoValue; +import javax.annotation.Nullable; +import org.apache.beam.sdk.schemas.AutoValueSchema; +import org.apache.beam.sdk.schemas.annotations.DefaultSchema; +import org.apache.beam.sdk.schemas.annotations.SchemaFieldDescription; +import org.apache.beam.sdk.schemas.transforms.providers.ErrorHandling; +import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Strings; + +/** + * Configuration for writing to Datadog. + * + * <p>This class is meant to be used with {@link DatadogWriteSchemaTransformProvider}. + */ +@DefaultSchema(AutoValueSchema.class) +@AutoValue +public abstract class DatadogWriteSchemaTransformConfiguration { + + public void validate() { + String invalidConfigMessage = "Invalid Datadog Write configuration: "; + + ErrorHandling errorHandling = getErrorHandling(); + if (errorHandling != null) { + checkArgument( + !Strings.isNullOrEmpty(errorHandling.getOutput()), + invalidConfigMessage + "Output must not be empty if error handling specified."); + } + } Review Comment:  The `validate()` method should ensure that mandatory fields like `url` and `apiKey` are not empty strings. Additionally, it should validate that numeric parameters such as `batchCount` and `parallelism` are positive to prevent runtime issues (e.g., `IllegalArgumentException` in `ThreadLocalRandom.nextInt`). ```suggestion public void validate() { String invalidConfigMessage = "Invalid Datadog Write configuration: "; checkArgument(!Strings.isNullOrEmpty(getUrl()), invalidConfigMessage + "url must be specified."); checkArgument(!Strings.isNullOrEmpty(getApiKey()), invalidConfigMessage + "apiKey must be specified."); if (getBatchCount() != null) { checkArgument(getBatchCount() > 0, invalidConfigMessage + "batchCount must be greater than 0."); } if (getParallelism() != null) { checkArgument(getParallelism() > 0, invalidConfigMessage + "parallelism must be greater than 0."); } ErrorHandling errorHandling = getErrorHandling(); if (errorHandling != null) { checkArgument( !Strings.isNullOrEmpty(errorHandling.getOutput()), invalidConfigMessage + "Output must not be empty if error handling specified."); } } ``` -- 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]
