PROPERTY_KEYS =
+ List.of(
+ "ratePerSecond",
+ "totalRecords",
+ "seriesCardinality",
+ "fieldsPerLine",
+ "measurement",
+ "runId");
+
+ private static final Pattern NAME_PATTERN = Pattern.compile("[A-Za-z0-9_-]{1,64}");
+
+ static DataGenConfig from(Properties properties) {
+ Properties group = properties == null ? new Properties() : properties;
+ for (String key : group.stringPropertyNames()) {
+ if (!PROPERTY_KEYS.contains(key)) {
+ throw new IllegalArgumentException(
+ "Unsupported property '"
+ + key
+ + "' in runtime property group '"
+ + ApplicationConfig.DATAGEN_PROPERTY_GROUP
+ + "'; supported properties are "
+ + PROPERTY_KEYS);
+ }
+ }
+
+ long ratePerSecond = longProperty(group, "ratePerSecond", DEFAULT_RATE_PER_SECOND);
+ long totalRecords = longProperty(group, "totalRecords", DEFAULT_TOTAL_RECORDS);
+ long seriesCardinality =
+ longProperty(group, "seriesCardinality", DEFAULT_SERIES_CARDINALITY);
+ long fieldsPerLine = longProperty(group, "fieldsPerLine", DEFAULT_FIELDS_PER_LINE);
+ String measurement = nameProperty(group, "measurement", DEFAULT_MEASUREMENT);
+ String runId = nameProperty(group, "runId", DEFAULT_RUN_ID);
+
+ require(ratePerSecond >= 0, "ratePerSecond", "must not be negative; 0 is unlimited");
+ require(totalRecords > 0, "totalRecords", "must be positive");
+ require(
+ seriesCardinality >= 1 && seriesCardinality <= MAX_SERIES_CARDINALITY,
+ "seriesCardinality",
+ "must be between 1 and " + MAX_SERIES_CARDINALITY);
+ require(
+ fieldsPerLine >= 1 && fieldsPerLine <= MAX_FIELDS_PER_LINE,
+ "fieldsPerLine",
+ "must be between 1 and " + MAX_FIELDS_PER_LINE);
+
+ return new DataGenConfig(
+ ratePerSecond,
+ totalRecords,
+ (int) seriesCardinality,
+ (int) fieldsPerLine,
+ measurement,
+ runId);
+ }
+
+ private static long longProperty(Properties group, String key, long defaultValue) {
+ String value = ApplicationConfig.optionalProperty(group, key);
+ if (value == null) {
+ return defaultValue;
+ }
+ try {
+ return Long.parseLong(value);
+ } catch (NumberFormatException e) {
+ throw invalid(key, "must be an integer, but was '" + value + "'", e);
+ }
+ }
+
+ private static String nameProperty(Properties group, String key, String defaultValue) {
+ String value = ApplicationConfig.optionalProperty(group, key);
+ if (value == null) {
+ return defaultValue;
+ }
+ require(
+ NAME_PATTERN.matcher(value).matches(),
+ key,
+ "must contain 1 to 64 letters, digits, hyphens, or underscores");
+ return value;
+ }
+
+ private static void require(boolean condition, String key, String message) {
+ if (!condition) {
+ throw invalid(key, message, null);
+ }
+ }
+
+ private static IllegalArgumentException invalid(
+ String key, String message, Exception cause) {
+ return new IllegalArgumentException(
+ "Property '"
+ + key
+ + "' in runtime property group '"
+ + ApplicationConfig.DATAGEN_PROPERTY_GROUP
+ + "' "
+ + message,
+ cause);
+ }
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/app/src/main/java/software/amazon/timestream/influxdb3/flink/examples/KinesisToInfluxDB3Application.java b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/app/src/main/java/software/amazon/timestream/influxdb3/flink/examples/KinesisToInfluxDB3Application.java
new file mode 100644
index 00000000..6177a520
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/app/src/main/java/software/amazon/timestream/influxdb3/flink/examples/KinesisToInfluxDB3Application.java
@@ -0,0 +1,182 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ */
+package software.amazon.timestream.influxdb3.flink.examples;
+
+import org.apache.flink.api.common.eventtime.WatermarkStrategy;
+import org.apache.flink.api.common.serialization.SimpleStringSchema;
+import org.apache.flink.api.common.typeinfo.Types;
+import org.apache.flink.api.connector.source.util.ratelimit.RateLimiterStrategy;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.connector.aws.config.AWSConfigOptions;
+import org.apache.flink.connector.datagen.source.DataGeneratorSource;
+import org.apache.flink.connector.kinesis.source.KinesisStreamsSource;
+import org.apache.flink.connector.kinesis.source.config.KinesisSourceConfigOptions;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
+
+import com.amazonaws.services.kinesisanalytics.runtime.KinesisAnalyticsRuntime;
+import software.amazon.timestream.influxdb3.flink.InfluxDB3Sink;
+import software.amazon.timestream.influxdb3.flink.InfluxDB3SinkBuilder;
+import software.amazon.timestream.influxdb3.flink.auth.SecretsManagerTokenProvider;
+
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Properties;
+
+/**
+ * Managed Flink example that writes Kinesis records to InfluxDB 3.
+ *
+ * The {@code Application.pipeline} runtime property selects the pipeline: {@code datastream}
+ * (default) forwards line protocol records through the DataStream API sink, {@code sql} runs
+ * {@link SqlPipeline}, and {@code datagen} writes generated line protocol for load tests without
+ * reading Kinesis.
+ */
+public final class KinesisToInfluxDB3Application {
+
+ static final String LOCAL_PROPERTIES_FILE_ENV = "APPLICATION_PROPERTIES_FILE";
+
+ private KinesisToInfluxDB3Application() {}
+
+ public static void main(String[] args) throws Exception {
+ ApplicationConfig config = ApplicationConfig.from(loadApplicationProperties());
+ StreamExecutionEnvironment environment =
+ StreamExecutionEnvironment.getExecutionEnvironment();
+
+ switch (config.pipeline()) {
+ case DATASTREAM -> {
+ buildPipeline(environment, config);
+ environment.execute("Kinesis to Timestream for InfluxDB 3");
+ }
+ // executeSql only submits the INSERT; await it so main blocks like execute() above.
+ case SQL -> SqlPipeline.execute(StreamTableEnvironment.create(environment), config)
+ .await();
+ case DATAGEN -> {
+ buildDataGenPipeline(environment, config, currentEpochNanos());
+ environment.execute("Generated line protocol to Timestream for InfluxDB 3");
+ }
+ }
+ }
+
+ static void buildPipeline(
+ StreamExecutionEnvironment environment, ApplicationConfig config) {
+ environment
+ .fromSource(
+ createKinesisSource(config),
+ WatermarkStrategy.noWatermarks(),
+ "kinesis-line-protocol-source")
+ .returns(Types.STRING)
+ .uid("kinesis-line-protocol-source")
+ .sinkTo(createInfluxSink(config))
+ .name("timestream-influxdb3-sink")
+ .uid("timestream-influxdb3-sink");
+ }
+
+ /**
+ * Builds the load-test pipeline, which generates line protocol in the job instead of reading
+ * Kinesis.
+ *
+ * @param startEpochNanos timestamp of the first generated row; captured once when the job is
+ * built so all subtasks and job restarts generate the same timestamps. An application
+ * update or restart builds the job again with a new value.
+ */
+ static void buildDataGenPipeline(
+ StreamExecutionEnvironment environment,
+ ApplicationConfig config,
+ long startEpochNanos) {
+ DataGenConfig dataGen = config.dataGen();
+ DataGeneratorSource source =
+ new DataGeneratorSource<>(
+ new LineProtocolGenerator(dataGen, startEpochNanos),
+ dataGen.totalRecords(),
+ dataGen.ratePerSecond() > 0
+ // Divided evenly across the source subtasks.
+ ? RateLimiterStrategy.perSecond(dataGen.ratePerSecond())
+ : RateLimiterStrategy.noOp(),
+ Types.STRING);
+ environment
+ .fromSource(
+ source, WatermarkStrategy.noWatermarks(), "datagen-line-protocol-source")
+ .uid("datagen-line-protocol-source")
+ .sinkTo(createInfluxSink(config))
+ .name("timestream-influxdb3-sink")
+ .uid("timestream-influxdb3-sink");
+ }
+
+ private static long currentEpochNanos() {
+ Instant now = Instant.now();
+ return Math.addExact(
+ Math.multiplyExact(now.getEpochSecond(), 1_000_000_000L), now.getNano());
+ }
+
+ static KinesisStreamsSource createKinesisSource(ApplicationConfig config) {
+ Configuration sourceConfiguration = new Configuration();
+ sourceConfiguration.set(AWSConfigOptions.AWS_REGION_OPTION, config.kinesisRegion());
+ sourceConfiguration.set(
+ KinesisSourceConfigOptions.STREAM_INITIAL_POSITION, config.initialPosition());
+ if (config.initialTimestamp() != null) {
+ sourceConfiguration.set(
+ KinesisSourceConfigOptions.STREAM_INITIAL_TIMESTAMP,
+ config.initialTimestamp());
+ }
+
+ return KinesisStreamsSource.builder()
+ .setStreamArn(config.streamArn())
+ .setSourceConfig(sourceConfiguration)
+ .setDeserializationSchema(new SimpleStringSchema())
+ .build();
+ }
+
+ static InfluxDB3Sink createInfluxSink(ApplicationConfig config) {
+ SecretsManagerTokenProvider.Builder tokenProvider =
+ SecretsManagerTokenProvider.builder()
+ .setSecretId(config.secretId())
+ .setRegion(config.secretRegion());
+ if (config.secretJsonField() != null) {
+ tokenProvider.setJsonField(config.secretJsonField());
+ }
+
+ InfluxDB3SinkBuilder builder =
+ InfluxDB3Sink.builder()
+ .setEndpoint(config.endpoint())
+ .setDatabase(config.database())
+ .setTokenProvider(tokenProvider.build())
+ .setConverter(KinesisToInfluxDB3Application::requireSingleLine)
+ .setManagedFlinkMetricsEnabled(true);
+ Optional.ofNullable(config.sinkIntOption("sink.batch.max-size"))
+ .ifPresent(builder::setMaxBatchSize);
+ Optional.ofNullable(config.sinkIntOption("sink.requests.max-buffered"))
+ .ifPresent(builder::setMaxBufferedRequests);
+ Optional.ofNullable(config.sinkIntOption("sink.requests.max-inflight"))
+ .ifPresent(builder::setMaxInFlightRequests);
+ Optional.ofNullable(config.sinkLongOption("sink.flush-buffer.size"))
+ .ifPresent(builder::setMaxBatchSizeInBytes);
+ Optional.ofNullable(config.sinkLongOption("sink.flush-buffer.timeout"))
+ .ifPresent(builder::setMaxTimeInBufferMS);
+ Optional.ofNullable(config.sinkIntOption("sink.max-retries"))
+ .ifPresent(builder::setMaxRetries);
+ return builder.build();
+ }
+
+ static String requireSingleLine(String lineProtocol) {
+ if (lineProtocol == null || lineProtocol.isBlank()) {
+ throw new IllegalArgumentException("Kinesis record must contain line protocol");
+ }
+ if (lineProtocol.indexOf('\n') >= 0 || lineProtocol.indexOf('\r') >= 0) {
+ throw new IllegalArgumentException(
+ "Each Kinesis record must contain exactly one line protocol row");
+ }
+ return lineProtocol;
+ }
+
+ private static Map loadApplicationProperties() throws IOException {
+ String localPropertiesFile = System.getenv(LOCAL_PROPERTIES_FILE_ENV);
+ if (localPropertiesFile != null && !localPropertiesFile.isBlank()) {
+ return KinesisAnalyticsRuntime.getApplicationProperties(localPropertiesFile);
+ }
+ return KinesisAnalyticsRuntime.getApplicationProperties();
+ }
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/app/src/main/java/software/amazon/timestream/influxdb3/flink/examples/LineProtocolGenerator.java b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/app/src/main/java/software/amazon/timestream/influxdb3/flink/examples/LineProtocolGenerator.java
new file mode 100644
index 00000000..0d9a443d
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/app/src/main/java/software/amazon/timestream/influxdb3/flink/examples/LineProtocolGenerator.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ */
+package software.amazon.timestream.influxdb3.flink.examples;
+
+import org.apache.flink.connector.datagen.source.GeneratorFunction;
+
+/**
+ * Generates one line protocol row per sequence number for the DATAGEN pipeline.
+ *
+ * Rows look like {@code loadtest,run=r1,host=host-0042 f0=12.34,f1=56.78 1760385600000001000}.
+ * The {@code host} tag cycles through {@code seriesCardinality} values. Field values and
+ * timestamps derive only from the sequence number, so a row regenerated after a job restart is
+ * identical and overwrites the earlier write instead of adding a point.
+ *
+ *
Timestamps start at {@code startEpochNanos} and advance by a fixed spacing per sequence
+ * number, so every row has a unique timestamp across all subtasks. At a configured rate the
+ * spacing is one second divided by the rate, which keeps timestamps near wall-clock time.
+ */
+final class LineProtocolGenerator implements GeneratorFunction {
+ private static final long serialVersionUID = 1L;
+
+ /** Spacing used when the rate is unlimited, equivalent to one million rows per second. */
+ static final long UNLIMITED_RATE_SPACING_NANOS = 1_000L;
+
+ private static final long NANOS_PER_SECOND = 1_000_000_000L;
+
+ private final String seriesPrefix;
+ private final int seriesCardinality;
+ private final int fieldsPerLine;
+ private final long startEpochNanos;
+ private final long spacingNanos;
+
+ LineProtocolGenerator(DataGenConfig config, long startEpochNanos) {
+ this.seriesPrefix = config.measurement() + ",run=" + config.runId() + ",host=host-";
+ this.seriesCardinality = config.seriesCardinality();
+ this.fieldsPerLine = config.fieldsPerLine();
+ this.startEpochNanos = startEpochNanos;
+ this.spacingNanos =
+ config.ratePerSecond() > 0
+ ? Math.max(1L, NANOS_PER_SECOND / config.ratePerSecond())
+ : UNLIMITED_RATE_SPACING_NANOS;
+ }
+
+ @Override
+ public String map(Long sequence) {
+ long value = sequence;
+ StringBuilder line = new StringBuilder(seriesPrefix.length() + 24 + fieldsPerLine * 12);
+ line.append(seriesPrefix).append(value % seriesCardinality).append(' ');
+ for (int field = 0; field < fieldsPerLine; field++) {
+ if (field > 0) {
+ line.append(',');
+ }
+ // Deterministic value from 0.00 to 99.99, varied per field.
+ long hundredths = Math.floorMod(value * 31 + field * 7919L, 10_000L);
+ line.append('f')
+ .append(field)
+ .append('=')
+ .append(hundredths / 100)
+ .append('.')
+ .append(hundredths % 100 < 10 ? "0" : "")
+ .append(hundredths % 100);
+ }
+ return line.append(' ').append(startEpochNanos + value * spacingNanos).toString();
+ }
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/app/src/main/java/software/amazon/timestream/influxdb3/flink/examples/SqlPipeline.java b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/app/src/main/java/software/amazon/timestream/influxdb3/flink/examples/SqlPipeline.java
new file mode 100644
index 00000000..a945c8fe
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/app/src/main/java/software/amazon/timestream/influxdb3/flink/examples/SqlPipeline.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ */
+package software.amazon.timestream.influxdb3.flink.examples;
+
+import org.apache.flink.configuration.PipelineOptions;
+import org.apache.flink.table.api.TableResult;
+import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Flink SQL pipeline that writes each JSON CPU reading from Kinesis as one InfluxDB 3 point
+ * through the {@code timestream-influxdb3} SQL sink.
+ *
+ * Each Kinesis record must contain one JSON reading, for example:
+ *
+ *
{@code
+ * {"host":"web-1","region":"us-east-1","usage":41.7,"ts":"2026-10-08T19:00:04.120Z"}
+ * }
+ *
+ * Points are written to the {@code cpu} measurement, named after the sink table.
+ */
+final class SqlPipeline {
+
+ static final String JOB_NAME = "Kinesis to Timestream for InfluxDB 3 (SQL)";
+
+ private SqlPipeline() {}
+
+ /** Creates the tables and submits the {@code INSERT} job without waiting for it to finish. */
+ static TableResult execute(StreamTableEnvironment tableEnvironment, ApplicationConfig config) {
+ configure(tableEnvironment);
+ createTables(tableEnvironment, config);
+ return tableEnvironment.executeSql(insertStatement());
+ }
+
+ static void configure(StreamTableEnvironment tableEnvironment) {
+ tableEnvironment.getConfig().set(PipelineOptions.NAME, JOB_NAME);
+ }
+
+ static void createTables(StreamTableEnvironment tableEnvironment, ApplicationConfig config) {
+ tableEnvironment.executeSql(sourceTableStatement(config));
+ tableEnvironment.executeSql(sinkTableStatement(config));
+ }
+
+ static String sourceTableStatement(ApplicationConfig config) {
+ List options = new ArrayList<>();
+ options.add(option("connector", "kinesis"));
+ options.add(option("stream.arn", config.streamArn()));
+ options.add(option("aws.region", config.kinesisRegion()));
+ options.add(option("source.init.position", config.initialPosition().name()));
+ if (config.initialTimestamp() != null) {
+ options.add(option("source.init.timestamp", config.initialTimestamp()));
+ }
+ options.add(option("format", "json"));
+ options.add(option("json.timestamp-format.standard", "ISO-8601"));
+
+ return "CREATE TABLE readings (\n"
+ + " host STRING,\n"
+ + " region STRING,\n"
+ + " usage DOUBLE,\n"
+ + " ts TIMESTAMP_LTZ(3)\n"
+ + ") WITH (\n"
+ + String.join(",\n", options)
+ + "\n)";
+ }
+
+ static String sinkTableStatement(ApplicationConfig config) {
+ List options = new ArrayList<>();
+ options.add(option("connector", "timestream-influxdb3"));
+ options.add(option("endpoint", config.endpoint()));
+ options.add(option("database", config.database()));
+ options.add(option("tag-columns", "host,region"));
+ options.add(option("timestamp-column", "time"));
+ options.add(option("precision", "ms"));
+ options.add(option("token.secret-id", config.secretId()));
+ if (config.secretJsonField() != null) {
+ options.add(option("token.secret-json-field", config.secretJsonField()));
+ }
+ options.add(option("token.secret-region", config.secretRegion()));
+ options.add(option("sink.metrics.managed-flink.enabled", "true"));
+ config.sinkOptions().forEach((key, value) -> options.add(option(key, value)));
+
+ return "CREATE TABLE cpu (\n"
+ + " host STRING,\n"
+ + " region STRING,\n"
+ + " usage DOUBLE,\n"
+ + " `time` TIMESTAMP_LTZ(3)\n"
+ + ") WITH (\n"
+ + String.join(",\n", options)
+ + "\n)";
+ }
+
+ /** Returns the job's {@code INSERT}, which writes one point per reading. */
+ static String insertStatement() {
+ return "INSERT INTO cpu SELECT host, region, usage, ts FROM readings";
+ }
+
+ private static String option(String key, String value) {
+ return " " + literal(key) + " = " + literal(value);
+ }
+
+ private static String literal(String value) {
+ return "'" + value.replace("'", "''") + "'";
+ }
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/app/src/test/java/software/amazon/timestream/influxdb3/flink/examples/ApplicationConfigTest.java b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/app/src/test/java/software/amazon/timestream/influxdb3/flink/examples/ApplicationConfigTest.java
new file mode 100644
index 00000000..d0689b2f
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/app/src/test/java/software/amazon/timestream/influxdb3/flink/examples/ApplicationConfigTest.java
@@ -0,0 +1,406 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ */
+package software.amazon.timestream.influxdb3.flink.examples;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
+
+import org.apache.flink.connector.kinesis.source.config.KinesisSourceConfigOptions.InitialPosition;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+
+import java.util.Map;
+import java.util.Properties;
+
+class ApplicationConfigTest {
+
+ @Test
+ void parsesRuntimePropertiesAndCreatesSink() {
+ Properties kinesis = properties("streamArn", streamArn(), "region", "us-east-1");
+ Properties influx =
+ properties(
+ "endpoint",
+ "https://example.test:8181",
+ "database",
+ "sensors",
+ "secretId",
+ "test/influxdb3/token",
+ "secretJsonField",
+ "token");
+
+ ApplicationConfig config =
+ ApplicationConfig.from(
+ Map.of(
+ ApplicationConfig.KINESIS_PROPERTY_GROUP,
+ kinesis,
+ ApplicationConfig.INFLUXDB3_PROPERTY_GROUP,
+ influx));
+
+ assertThat(config.pipeline()).isEqualTo(ApplicationConfig.Pipeline.DATASTREAM);
+ assertThat(config.initialPosition()).isEqualTo(InitialPosition.LATEST);
+ assertThat(config.secretRegion()).isEqualTo("us-east-1");
+
+ assertThat(config.endpoint()).isEqualTo("https://example.test:8181");
+ assertThat(config.database()).isEqualTo("sensors");
+ assertThat(config.secretId()).isEqualTo("test/influxdb3/token");
+ assertThat(config.sinkOptions()).isEmpty();
+ assertThat(KinesisToInfluxDB3Application.createInfluxSink(config)).isNotNull();
+ }
+
+ @Test
+ void parsesOptionalSinkTuningProperties() {
+ ApplicationConfig config =
+ withSink(
+ properties(
+ "sink.batch.max-size", " 50000 ",
+ "sink.requests.max-buffered", "100000",
+ "sink.requests.max-inflight", "4",
+ "sink.flush-buffer.size", "20971520",
+ "sink.flush-buffer.timeout", "1000",
+ "sink.max-retries", "3"));
+
+ assertThat(config.sinkOptions())
+ .containsExactly(
+ Map.entry("sink.batch.max-size", "50000"),
+ Map.entry("sink.requests.max-buffered", "100000"),
+ Map.entry("sink.requests.max-inflight", "4"),
+ Map.entry("sink.flush-buffer.size", "20971520"),
+ Map.entry("sink.flush-buffer.timeout", "1000"),
+ Map.entry("sink.max-retries", "3"));
+ assertThat(config.sinkIntOption("sink.batch.max-size")).isEqualTo(50_000);
+ assertThat(config.sinkLongOption("sink.flush-buffer.size")).isEqualTo(20_971_520L);
+ assertThat(config.sinkIntOption("sink.requests.max-inflight")).isEqualTo(4);
+ assertThat(KinesisToInfluxDB3Application.createInfluxSink(config)).isNotNull();
+ }
+
+ @Test
+ void rejectsUnknownSinkProperties() {
+ assertThatIllegalArgumentException()
+ .isThrownBy(() -> withSink(properties("sink.batch.max-sizes", "100")))
+ .withMessageContaining("Unsupported property 'sink.batch.max-sizes'")
+ .withMessageContaining("'Sink'");
+ }
+
+ @Test
+ void rejectsNonIntegerSinkProperties() {
+ ApplicationConfig config = withSink(properties("sink.batch.max-size", "10k"));
+
+ assertThatIllegalArgumentException()
+ .isThrownBy(() -> KinesisToInfluxDB3Application.createInfluxSink(config))
+ .withMessage(
+ "Property 'sink.batch.max-size' in runtime property group 'Sink' "
+ + "must be an integer, but was '10k'");
+ }
+
+ /** Each case is rejected by the connector, which proves the value reached the builder. */
+ @ParameterizedTest(name = "{0}={1}")
+ @CsvSource({
+ "sink.batch.max-size, 0, maxBatchSize",
+ "sink.requests.max-buffered, 10000, maxBufferedRequests must be greater than maxBatchSize",
+ "sink.requests.max-inflight, 0, maxInFlightRequests",
+ "sink.flush-buffer.size, 1024, maxBatchSizeInBytes must be at least maxRecordSizeInBytes",
+ "sink.flush-buffer.timeout, 0, maxTimeInBufferMillis",
+ "sink.max-retries, -1, maxRetries must not be negative"
+ })
+ void appliesSinkPropertiesToTheConnector(String key, String value, String message) {
+ ApplicationConfig config = withSink(properties(key, value));
+
+ assertThatIllegalArgumentException()
+ .isThrownBy(() -> KinesisToInfluxDB3Application.createInfluxSink(config))
+ .withMessageContaining(message);
+ }
+
+ @Test
+ void parsesTrimHorizonCaseInsensitively() {
+ Properties kinesis =
+ properties(
+ "streamArn",
+ streamArn(),
+ "region",
+ "us-east-1",
+ "initialPosition",
+ "trim_horizon");
+
+ ApplicationConfig config =
+ ApplicationConfig.from(
+ Map.of(
+ ApplicationConfig.KINESIS_PROPERTY_GROUP,
+ kinesis,
+ ApplicationConfig.INFLUXDB3_PROPERTY_GROUP,
+ influxProperties()));
+
+ assertThat(config.initialPosition()).isEqualTo(InitialPosition.TRIM_HORIZON);
+ }
+
+ @Test
+ void parsesTheSqlPipelineCaseInsensitively() {
+ ApplicationConfig config =
+ ApplicationConfig.from(
+ Map.of(
+ ApplicationConfig.APPLICATION_PROPERTY_GROUP,
+ properties("pipeline", "Sql"),
+ ApplicationConfig.KINESIS_PROPERTY_GROUP,
+ properties("streamArn", streamArn(), "region", "us-east-1"),
+ ApplicationConfig.INFLUXDB3_PROPERTY_GROUP,
+ influxProperties()));
+
+ assertThat(config.pipeline()).isEqualTo(ApplicationConfig.Pipeline.SQL);
+ }
+
+ @Test
+ void rejectsUnknownPipelines() {
+ assertThatIllegalArgumentException()
+ .isThrownBy(
+ () ->
+ ApplicationConfig.from(
+ Map.of(
+ ApplicationConfig.APPLICATION_PROPERTY_GROUP,
+ properties("pipeline", "table"),
+ ApplicationConfig.KINESIS_PROPERTY_GROUP,
+ properties(
+ "streamArn",
+ streamArn(),
+ "region",
+ "us-east-1"),
+ ApplicationConfig.INFLUXDB3_PROPERTY_GROUP,
+ influxProperties())))
+ .withMessageContaining("must be DATASTREAM, SQL, or DATAGEN");
+ }
+
+ @Test
+ void rejectsPlaintextTokenRuntimeProperty() {
+ Properties kinesis = properties("streamArn", streamArn(), "region", "us-east-1");
+ Properties influx =
+ properties(
+ "endpoint",
+ "https://example.test:8181",
+ "database",
+ "sensors",
+ "token",
+ "temporary-token");
+
+ assertThatIllegalArgumentException()
+ .isThrownBy(
+ () ->
+ ApplicationConfig.from(
+ Map.of(
+ ApplicationConfig.KINESIS_PROPERTY_GROUP,
+ kinesis,
+ ApplicationConfig.INFLUXDB3_PROPERTY_GROUP,
+ influx)))
+ .withMessageContaining("not supported")
+ .withMessageContaining("Secrets Manager");
+ }
+
+ @Test
+ void rejectsPlaintextTokenEvenWhenSecretIdIsConfigured() {
+ Properties kinesis = properties("streamArn", streamArn(), "region", "us-east-1");
+ Properties influx =
+ properties(
+ "endpoint",
+ "https://example.test:8181",
+ "database",
+ "sensors",
+ "token",
+ "temporary-token",
+ "secretId",
+ "test/influxdb3/token");
+
+ assertThatIllegalArgumentException()
+ .isThrownBy(
+ () ->
+ ApplicationConfig.from(
+ Map.of(
+ ApplicationConfig.KINESIS_PROPERTY_GROUP,
+ kinesis,
+ ApplicationConfig.INFLUXDB3_PROPERTY_GROUP,
+ influx)))
+ .withMessageContaining("not supported");
+ }
+
+ @Test
+ void requiresSecretId() {
+ Properties kinesis = properties("streamArn", streamArn(), "region", "us-east-1");
+ Properties influx =
+ properties(
+ "endpoint",
+ "https://example.test:8181",
+ "database",
+ "sensors");
+
+ assertThatIllegalArgumentException()
+ .isThrownBy(
+ () ->
+ ApplicationConfig.from(
+ Map.of(
+ ApplicationConfig.KINESIS_PROPERTY_GROUP,
+ kinesis,
+ ApplicationConfig.INFLUXDB3_PROPERTY_GROUP,
+ influx)))
+ .withMessageContaining("secretId");
+ }
+
+ @Test
+ void requiresTimestampForAtTimestampPosition() {
+ Properties kinesis =
+ properties(
+ "streamArn",
+ streamArn(),
+ "region",
+ "us-east-1",
+ "initialPosition",
+ "AT_TIMESTAMP");
+
+ assertThatIllegalArgumentException()
+ .isThrownBy(
+ () ->
+ ApplicationConfig.from(
+ Map.of(
+ ApplicationConfig.KINESIS_PROPERTY_GROUP,
+ kinesis,
+ ApplicationConfig.INFLUXDB3_PROPERTY_GROUP,
+ influxProperties())))
+ .withMessageContaining("initialTimestamp");
+ }
+
+ @Test
+ void reportsMissingPropertyGroup() {
+ assertThatIllegalArgumentException()
+ .isThrownBy(() -> ApplicationConfig.from(Map.of()))
+ .withMessage("Missing runtime property group 'KinesisSource'");
+ }
+
+ @Test
+ void rejectsMultipleLineProtocolRowsInOneRecord() {
+ assertThatIllegalArgumentException()
+ .isThrownBy(
+ () ->
+ KinesisToInfluxDB3Application.requireSingleLine(
+ "a value=1\nb value=2"))
+ .withMessageContaining("exactly one");
+ }
+
+ @Test
+ void buildsSourceToSinkJobGraphWithExplicitStringType() {
+ ApplicationConfig config =
+ ApplicationConfig.from(
+ Map.of(
+ ApplicationConfig.KINESIS_PROPERTY_GROUP,
+ properties(
+ "streamArn",
+ streamArn(),
+ "region",
+ "us-east-1"),
+ ApplicationConfig.INFLUXDB3_PROPERTY_GROUP,
+ influxProperties()));
+ StreamExecutionEnvironment environment =
+ StreamExecutionEnvironment.getExecutionEnvironment();
+
+ KinesisToInfluxDB3Application.buildPipeline(environment, config);
+
+ assertThat(environment.getStreamGraph().getStreamNodes()).hasSize(2);
+ }
+
+ @Test
+ void parsesTheDataGenPipelineWithoutAKinesisSource() {
+ Properties influx = influxProperties();
+ influx.remove("secretJsonField");
+ ApplicationConfig config =
+ ApplicationConfig.from(
+ Map.of(
+ ApplicationConfig.APPLICATION_PROPERTY_GROUP,
+ properties("pipeline", "datagen"),
+ ApplicationConfig.INFLUXDB3_PROPERTY_GROUP,
+ influx,
+ ApplicationConfig.DATAGEN_PROPERTY_GROUP,
+ properties("ratePerSecond", "1000", "runId", "smoke")));
+
+ assertThat(config.pipeline()).isEqualTo(ApplicationConfig.Pipeline.DATAGEN);
+ assertThat(config.streamArn()).isNull();
+ assertThat(config.kinesisRegion()).isNull();
+ // Falls back to the AWS SDK region chain at runtime.
+ assertThat(config.secretRegion()).isNull();
+ assertThat(config.dataGen().ratePerSecond()).isEqualTo(1_000);
+ assertThat(config.dataGen().runId()).isEqualTo("smoke");
+ assertThat(config.dataGen().seriesCardinality())
+ .isEqualTo(DataGenConfig.DEFAULT_SERIES_CARDINALITY);
+ }
+
+ @Test
+ void ignoresTheDataGenGroupForOtherPipelines() {
+ ApplicationConfig config =
+ ApplicationConfig.from(
+ Map.of(
+ ApplicationConfig.KINESIS_PROPERTY_GROUP,
+ properties("streamArn", streamArn(), "region", "us-east-1"),
+ ApplicationConfig.INFLUXDB3_PROPERTY_GROUP,
+ influxProperties(),
+ ApplicationConfig.DATAGEN_PROPERTY_GROUP,
+ properties("ratePerSecond", "1000")));
+
+ assertThat(config.dataGen()).isNull();
+ }
+
+ @Test
+ void buildsGeneratorToSinkJobGraph() {
+ ApplicationConfig config =
+ ApplicationConfig.from(
+ Map.of(
+ ApplicationConfig.APPLICATION_PROPERTY_GROUP,
+ properties("pipeline", "DATAGEN"),
+ ApplicationConfig.INFLUXDB3_PROPERTY_GROUP,
+ influxProperties(),
+ ApplicationConfig.DATAGEN_PROPERTY_GROUP,
+ properties("ratePerSecond", "100")));
+ StreamExecutionEnvironment environment =
+ StreamExecutionEnvironment.getExecutionEnvironment();
+
+ KinesisToInfluxDB3Application.buildDataGenPipeline(
+ environment, config, 1_760_000_000_000_000_000L);
+
+ assertThat(environment.getStreamGraph().getStreamNodes())
+ .hasSize(2)
+ .extracting(node -> node.getOperatorName())
+ .anySatisfy(name -> assertThat(name).contains("datagen-line-protocol-source"))
+ .anySatisfy(name -> assertThat(name).contains("timestream-influxdb3-sink"));
+ }
+
+ private static ApplicationConfig withSink(Properties sink) {
+ return ApplicationConfig.from(
+ Map.of(
+ ApplicationConfig.KINESIS_PROPERTY_GROUP,
+ properties("streamArn", streamArn(), "region", "us-east-1"),
+ ApplicationConfig.INFLUXDB3_PROPERTY_GROUP,
+ influxProperties(),
+ ApplicationConfig.SINK_PROPERTY_GROUP,
+ sink));
+ }
+
+ private static Properties influxProperties() {
+ return properties(
+ "endpoint",
+ "https://example.test:8181",
+ "database",
+ "sensors",
+ "secretId",
+ "test/influxdb3/token",
+ "secretJsonField",
+ "token");
+ }
+
+ private static String streamArn() {
+ return "arn:aws:kinesis:us-east-1:123456789012:stream/influxdb3-example-input";
+ }
+
+ private static Properties properties(String... values) {
+ Properties properties = new Properties();
+ for (int index = 0; index < values.length; index += 2) {
+ properties.setProperty(values[index], values[index + 1]);
+ }
+ return properties;
+ }
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/app/src/test/java/software/amazon/timestream/influxdb3/flink/examples/DataGenConfigTest.java b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/app/src/test/java/software/amazon/timestream/influxdb3/flink/examples/DataGenConfigTest.java
new file mode 100644
index 00000000..8e552ee5
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/app/src/test/java/software/amazon/timestream/influxdb3/flink/examples/DataGenConfigTest.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ */
+package software.amazon.timestream.influxdb3.flink.examples;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
+
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.api.Test;
+
+import java.util.Properties;
+
+class DataGenConfigTest {
+
+ @Test
+ void appliesDefaultsWhenTheGroupIsMissing() {
+ assertThat(DataGenConfig.from(null))
+ .isEqualTo(
+ new DataGenConfig(
+ 0, Long.MAX_VALUE, 1_000, 4, "loadtest", "default"));
+ }
+
+ @Test
+ void parsesEveryProperty() {
+ Properties properties = new Properties();
+ properties.setProperty("ratePerSecond", "5000");
+ properties.setProperty("totalRecords", "1000000");
+ properties.setProperty("seriesCardinality", "20");
+ properties.setProperty("fieldsPerLine", " 8 ");
+ properties.setProperty("measurement", "cpu_load");
+ properties.setProperty("runId", "p4-b10k");
+
+ assertThat(DataGenConfig.from(properties))
+ .isEqualTo(new DataGenConfig(5_000, 1_000_000, 20, 8, "cpu_load", "p4-b10k"));
+ }
+
+ @ParameterizedTest(name = "{0}={1}")
+ @CsvSource({
+ "ratePerSecond, -1, must not be negative",
+ "ratePerSecond, fast, must be an integer, but was 'fast'",
+ "totalRecords, 0, must be positive",
+ "seriesCardinality, 0, must be between 1 and 10000000",
+ "seriesCardinality, 10000001, must be between 1 and 10000000",
+ "fieldsPerLine, 101, must be between 1 and 100",
+ "measurement, cpu load, must contain 1 to 64 letters",
+ "runId, 'r1,host=x', must contain 1 to 64 letters",
+ "rate, 10, Unsupported property 'rate'"
+ })
+ void rejectsInvalidProperties(String key, String value, String message) {
+ Properties properties = new Properties();
+ properties.setProperty(key, value);
+
+ assertThatIllegalArgumentException()
+ .isThrownBy(() -> DataGenConfig.from(properties))
+ .withMessageContaining(message)
+ .withMessageContaining("'DataGen'");
+ }
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/app/src/test/java/software/amazon/timestream/influxdb3/flink/examples/LineProtocolGeneratorTest.java b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/app/src/test/java/software/amazon/timestream/influxdb3/flink/examples/LineProtocolGeneratorTest.java
new file mode 100644
index 00000000..fa2c5801
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/app/src/test/java/software/amazon/timestream/influxdb3/flink/examples/LineProtocolGeneratorTest.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ */
+package software.amazon.timestream.influxdb3.flink.examples;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.HashSet;
+import java.util.Set;
+
+class LineProtocolGeneratorTest {
+
+ private static final long START = 1_760_000_000_000_000_000L;
+
+ @Test
+ void generatesDeterministicLineProtocol() {
+ LineProtocolGenerator generator = generator(1_000, 100, 2);
+
+ assertThat(generator.map(42L))
+ .isEqualTo("loadtest,run=r1,host=host-42 f0=13.02,f1=92.21 1760000000042000000");
+ assertThat(generator.map(42L)).isEqualTo(generator.map(42L));
+ }
+
+ @Test
+ void padsFieldValuesToTwoDecimalPlaces() {
+ LineProtocolGenerator generator = generator(1_000, 100, 1);
+
+ assertThat(generator.map(0L)).contains(" f0=0.00 ");
+ }
+
+ @Test
+ void cyclesTheHostTagThroughTheSeriesCardinality() {
+ LineProtocolGenerator generator = generator(1_000, 100, 1);
+
+ assertThat(generator.map(142L)).startsWith("loadtest,run=r1,host=host-42 ");
+ assertThat(generator.map(99L)).startsWith("loadtest,run=r1,host=host-99 ");
+ assertThat(generator.map(100L)).startsWith("loadtest,run=r1,host=host-0 ");
+ }
+
+ @Test
+ void spacesTimestampsByTheConfiguredRate() {
+ assertThat(timestamp(generator(1_000, 10, 1).map(1L))).isEqualTo(START + 1_000_000L);
+ assertThat(timestamp(generator(3, 10, 1).map(1L))).isEqualTo(START + 333_333_333L);
+ assertThat(timestamp(generator(2_000_000_000L, 10, 1).map(1L))).isEqualTo(START + 1L);
+ assertThat(timestamp(generator(0, 10, 1).map(1L)))
+ .isEqualTo(START + LineProtocolGenerator.UNLIMITED_RATE_SPACING_NANOS);
+ }
+
+ @Test
+ void givesEveryRowOfASeriesAUniqueTimestamp() {
+ LineProtocolGenerator generator = generator(0, 7, 3);
+ Set seriesAndTimestamps = new HashSet<>();
+
+ for (long sequence = 0; sequence < 10_000; sequence++) {
+ String line = generator.map(sequence);
+ String series = line.substring(0, line.indexOf(' '));
+ assertThat(seriesAndTimestamps.add(series + "@" + timestamp(line))).isTrue();
+ }
+ }
+
+ private static LineProtocolGenerator generator(
+ long ratePerSecond, int seriesCardinality, int fieldsPerLine) {
+ return new LineProtocolGenerator(
+ new DataGenConfig(
+ ratePerSecond,
+ Long.MAX_VALUE,
+ seriesCardinality,
+ fieldsPerLine,
+ "loadtest",
+ "r1"),
+ START);
+ }
+
+ private static long timestamp(String line) {
+ return Long.parseLong(line.substring(line.lastIndexOf(' ') + 1));
+ }
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/app/src/test/java/software/amazon/timestream/influxdb3/flink/examples/ManagedFlinkExampleShadedJarVerifier.java b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/app/src/test/java/software/amazon/timestream/influxdb3/flink/examples/ManagedFlinkExampleShadedJarVerifier.java
new file mode 100644
index 00000000..4ab860c5
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/app/src/test/java/software/amazon/timestream/influxdb3/flink/examples/ManagedFlinkExampleShadedJarVerifier.java
@@ -0,0 +1,142 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ */
+package software.amazon.timestream.influxdb3.flink.examples;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.reflect.Method;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.jar.Attributes;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+import java.util.jar.Manifest;
+
+/** Post-package assertions for the deployable Managed Flink application JAR. */
+public final class ManagedFlinkExampleShadedJarVerifier {
+ private static final String MAIN_CLASS =
+ "software.amazon.timestream.influxdb3.flink.examples.KinesisToInfluxDB3Application";
+ private static final String SHADED_PREFIX =
+ "software/amazon/timestream/influxdb3/flink/examples/shaded/";
+ private static final String TABLE_FACTORY_SERVICES =
+ "META-INF/services/org.apache.flink.table.factories.Factory";
+ /** Factories the SQL pipeline discovers: Kinesis source, JSON format, and InfluxDB 3 sink. */
+ private static final List SQL_PIPELINE_FACTORIES =
+ List.of(
+ "org.apache.flink.connector.kinesis.table.KinesisDynamicTableFactory",
+ "org.apache.flink.formats.json.JsonFormatFactory",
+ "software.amazon.timestream.influxdb3.flink.table.InfluxDB3DynamicTableSinkFactory");
+
+ private ManagedFlinkExampleShadedJarVerifier() {}
+
+ public static void main(String[] arguments) throws Exception {
+ if (arguments.length != 1) {
+ throw new IllegalArgumentException("Expected the shaded JAR path");
+ }
+ Path shadedJar = Path.of(arguments[0]);
+ if (!Files.isRegularFile(shadedJar)) {
+ throw new IllegalStateException("Shaded JAR does not exist: " + shadedJar);
+ }
+
+ Set classes = new HashSet<>();
+ boolean hasLicense = false;
+ boolean hasNotice = false;
+ try (JarFile jar = new JarFile(shadedJar.toFile())) {
+ Manifest manifest = jar.getManifest();
+ String manifestMainClass =
+ manifest == null
+ ? null
+ : manifest.getMainAttributes().getValue(Attributes.Name.MAIN_CLASS);
+ if (!MAIN_CLASS.equals(manifestMainClass)) {
+ throw new IllegalStateException(
+ "Unexpected shaded JAR Main-Class: " + manifestMainClass);
+ }
+
+ var iterator = jar.entries();
+ while (iterator.hasMoreElements()) {
+ JarEntry entry = iterator.nextElement();
+ if (entry.getName().endsWith(".class")
+ && !classes.add(entry.getName())) {
+ throw new IllegalStateException(
+ "Duplicate class in shaded JAR: " + entry.getName());
+ }
+ if (entry.getName().startsWith("META-INF/native/")
+ && entry.getName().contains("netty_tcnative")) {
+ throw new IllegalStateException(
+ "Relocation-incompatible tcnative resource: " + entry.getName());
+ }
+ hasLicense |= "META-INF/LICENSE.txt".equals(entry.getName());
+ hasNotice |= "META-INF/NOTICE".equals(entry.getName());
+ }
+ requireTableFactories(jar);
+ }
+ if (!classes.contains(MAIN_CLASS.replace('.', '/') + ".class")) {
+ throw new IllegalStateException("Shaded JAR is missing its application entry point");
+ }
+ if (!hasLicense || !hasNotice) {
+ throw new IllegalStateException(
+ "Shaded JAR must contain META-INF/LICENSE.txt and META-INF/NOTICE");
+ }
+
+ requirePackage(classes, SHADED_PREFIX + "io/netty/");
+ requirePackage(classes, SHADED_PREFIX + "io/grpc/");
+ requirePackage(classes, SHADED_PREFIX + "com/google/common/");
+ requirePackage(classes, SHADED_PREFIX + "com/google/protobuf/");
+ rejectPackage(classes, "io/netty/");
+ rejectPackage(classes, "io/grpc/");
+ rejectPackage(classes, "com/google/common/");
+ rejectPackage(classes, "com/google/protobuf/");
+
+ try (URLClassLoader isolated =
+ new URLClassLoader(
+ new URL[] {shadedJar.toUri().toURL()},
+ ClassLoader.getPlatformClassLoader())) {
+ Class> openSsl =
+ isolated.loadClass(
+ "software.amazon.timestream.influxdb3.flink.examples.shaded.io.netty.handler.ssl.OpenSsl");
+ Method isAvailable = openSsl.getMethod("isAvailable");
+ if (Boolean.TRUE.equals(isAvailable.invoke(null))) {
+ throw new IllegalStateException(
+ "Shaded Netty unexpectedly loaded an unverified native TLS provider");
+ }
+ }
+ }
+
+ private static void requireTableFactories(JarFile jar) throws IOException {
+ JarEntry services = jar.getJarEntry(TABLE_FACTORY_SERVICES);
+ if (services == null) {
+ throw new IllegalStateException("Shaded JAR is missing " + TABLE_FACTORY_SERVICES);
+ }
+ String registered;
+ try (InputStream input = jar.getInputStream(services)) {
+ registered = new String(input.readAllBytes(), StandardCharsets.UTF_8);
+ }
+ Set factories = new HashSet<>(registered.lines().map(String::trim).toList());
+ for (String factory : SQL_PIPELINE_FACTORIES) {
+ if (!factories.contains(factory)) {
+ throw new IllegalStateException(
+ TABLE_FACTORY_SERVICES + " does not register " + factory);
+ }
+ }
+ }
+
+ private static void requirePackage(Set entries, String prefix) {
+ if (entries.stream().noneMatch(entry -> entry.startsWith(prefix))) {
+ throw new IllegalStateException("Missing relocated package " + prefix);
+ }
+ }
+
+ private static void rejectPackage(Set entries, String prefix) {
+ if (entries.stream().anyMatch(entry -> entry.startsWith(prefix))) {
+ throw new IllegalStateException("Found unrelocated package " + prefix);
+ }
+ }
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/app/src/test/java/software/amazon/timestream/influxdb3/flink/examples/SqlPipelineTest.java b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/app/src/test/java/software/amazon/timestream/influxdb3/flink/examples/SqlPipelineTest.java
new file mode 100644
index 00000000..535dd187
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/app/src/test/java/software/amazon/timestream/influxdb3/flink/examples/SqlPipelineTest.java
@@ -0,0 +1,157 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ */
+package software.amazon.timestream.influxdb3.flink.examples;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.table.api.TableException;
+import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
+import org.junit.jupiter.api.Test;
+
+import java.util.Map;
+import java.util.Properties;
+
+class SqlPipelineTest {
+
+ @Test
+ void plansAOnePointPerReadingInsertIntoTheInfluxDB3SqlSink() {
+ StreamTableEnvironment tableEnvironment = tableEnvironment();
+ SqlPipeline.configure(tableEnvironment);
+ SqlPipeline.createTables(tableEnvironment, config(Map.of()));
+
+ String plan = tableEnvironment.explainSql(SqlPipeline.insertStatement());
+
+ assertThat(plan)
+ .contains("TableSourceScan(table=[[default_catalog, default_database, readings]]")
+ .contains("Sink(table=[default_catalog.default_database.cpu]")
+ .doesNotContain("Aggregate");
+ }
+
+ @Test
+ void rejectsAnUpdatingQueryBecauseTheSinkIsInsertOnly() {
+ StreamTableEnvironment tableEnvironment = tableEnvironment();
+ SqlPipeline.createTables(tableEnvironment, config(Map.of()));
+
+ assertThatThrownBy(
+ () ->
+ tableEnvironment.explainSql(
+ "INSERT INTO cpu SELECT host, region, AVG(usage), "
+ + "MAX(ts) FROM readings GROUP BY host, region"))
+ .isInstanceOf(TableException.class)
+ .hasMessageContaining("doesn't support consuming update");
+ }
+
+ @Test
+ void writesRuntimePropertiesIntoTheTableOptions() {
+ ApplicationConfig config =
+ config(Map.of("database", "it's-quoted"));
+
+ assertThat(SqlPipeline.sourceTableStatement(config))
+ .contains("'stream.arn' = '" + streamArn() + "'")
+ .contains("'aws.region' = 'us-east-1'")
+ .contains("'source.init.position' = 'LATEST'")
+ .doesNotContain("source.init.timestamp");
+ assertThat(SqlPipeline.sinkTableStatement(config))
+ .contains("'connector' = 'timestream-influxdb3'")
+ .doesNotContain("'measurement'")
+ .contains("'database' = 'it''s-quoted'")
+ .contains("'token.secret-id' = 'test/influxdb3/token'")
+ .contains("'token.secret-json-field' = 'token'")
+ .contains("'token.secret-region' = 'us-east-1'")
+ .contains("'sink.metrics.managed-flink.enabled' = 'true'")
+ .doesNotContain("'token' =");
+ }
+
+ @Test
+ void passesTheInitialTimestampToTheKinesisSource() {
+ ApplicationConfig config =
+ ApplicationConfig.from(
+ Map.of(
+ ApplicationConfig.APPLICATION_PROPERTY_GROUP,
+ properties("pipeline", "sql"),
+ ApplicationConfig.KINESIS_PROPERTY_GROUP,
+ properties(
+ "streamArn", streamArn(),
+ "region", "us-east-1",
+ "initialPosition", "AT_TIMESTAMP",
+ "initialTimestamp", "2026-10-08T19:00:00.000Z"),
+ ApplicationConfig.INFLUXDB3_PROPERTY_GROUP,
+ influxProperties(Map.of())));
+
+ assertThat(SqlPipeline.sourceTableStatement(config))
+ .contains("'source.init.position' = 'AT_TIMESTAMP'")
+ .contains("'source.init.timestamp' = '2026-10-08T19:00:00.000Z'");
+ }
+
+ @Test
+ void passesSinkTuningPropertiesToTheSqlSink() {
+ ApplicationConfig config =
+ ApplicationConfig.from(
+ Map.of(
+ ApplicationConfig.APPLICATION_PROPERTY_GROUP,
+ properties("pipeline", "sql"),
+ ApplicationConfig.KINESIS_PROPERTY_GROUP,
+ properties("streamArn", streamArn(), "region", "us-east-1"),
+ ApplicationConfig.INFLUXDB3_PROPERTY_GROUP,
+ influxProperties(Map.of()),
+ ApplicationConfig.SINK_PROPERTY_GROUP,
+ properties(
+ "sink.batch.max-size", "50000",
+ "sink.requests.max-buffered", "100000",
+ "sink.flush-buffer.timeout", "1000")));
+
+ assertThat(SqlPipeline.sinkTableStatement(config))
+ .contains("'sink.batch.max-size' = '50000'")
+ .contains("'sink.requests.max-buffered' = '100000'")
+ .contains("'sink.flush-buffer.timeout' = '1000'")
+ .doesNotContain("sink.requests.max-inflight");
+
+ StreamTableEnvironment tableEnvironment = tableEnvironment();
+ SqlPipeline.createTables(tableEnvironment, config);
+ assertThat(tableEnvironment.explainSql(SqlPipeline.insertStatement()))
+ .contains("Sink(table=[default_catalog.default_database.cpu]");
+ }
+
+ private static StreamTableEnvironment tableEnvironment() {
+ return StreamTableEnvironment.create(
+ StreamExecutionEnvironment.getExecutionEnvironment());
+ }
+
+ private static ApplicationConfig config(Map influxOverrides) {
+ return ApplicationConfig.from(
+ Map.of(
+ ApplicationConfig.APPLICATION_PROPERTY_GROUP,
+ properties("pipeline", "sql"),
+ ApplicationConfig.KINESIS_PROPERTY_GROUP,
+ properties("streamArn", streamArn(), "region", "us-east-1"),
+ ApplicationConfig.INFLUXDB3_PROPERTY_GROUP,
+ influxProperties(influxOverrides)));
+ }
+
+ private static Properties influxProperties(Map overrides) {
+ Properties properties =
+ properties(
+ "endpoint", "https://example.test:8181",
+ "database", "sensors",
+ "secretId", "test/influxdb3/token",
+ "secretJsonField", "token");
+ properties.putAll(overrides);
+ return properties;
+ }
+
+ private static String streamArn() {
+ return "arn:aws:kinesis:us-east-1:123456789012:stream/influxdb3-example-input";
+ }
+
+ private static Properties properties(String... values) {
+ Properties properties = new Properties();
+ for (int index = 0; index < values.length; index += 2) {
+ properties.setProperty(values[index], values[index + 1]);
+ }
+ return properties;
+ }
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/infra/bin/app.ts b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/infra/bin/app.ts
new file mode 100644
index 00000000..6e52e1de
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/infra/bin/app.ts
@@ -0,0 +1,152 @@
+#!/usr/bin/env node
+
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as cdk from 'aws-cdk-lib';
+import { ManagedFlinkExampleStack } from '../lib/managed-flink-example-stack';
+
+function stringContext(app: cdk.App, key: string, defaultValue: string): string {
+ const value = app.node.tryGetContext(key);
+ return value === undefined ? defaultValue : String(value);
+}
+
+function optionalStringContext(app: cdk.App, key: string): string | undefined {
+ const value = app.node.tryGetContext(key);
+ if (value === undefined) {
+ return undefined;
+ }
+ const parsed = String(value).trim();
+ if (parsed.length === 0) {
+ throw new Error(`CDK context '${key}' must not be blank`);
+ }
+ return parsed;
+}
+
+function stringListContext(app: cdk.App, key: string): string[] | undefined {
+ const value = app.node.tryGetContext(key);
+ if (value === undefined) {
+ return undefined;
+ }
+
+ const values = Array.isArray(value)
+ ? value.map(String)
+ : String(value).split(',');
+ const parsed = values.map((item) => item.trim()).filter(Boolean);
+ if (parsed.length === 0) {
+ throw new Error(`CDK context '${key}' must contain at least one ID`);
+ }
+ return parsed;
+}
+
+function optionalNumberContext(app: cdk.App, key: string): number | undefined {
+ const value = optionalStringContext(app, key);
+ if (value === undefined) {
+ return undefined;
+ }
+ const parsed = Number(value);
+ if (!Number.isFinite(parsed)) {
+ throw new Error(`CDK context '${key}' must be a number`);
+ }
+ return parsed;
+}
+
+function optionalBooleanContext(app: cdk.App, key: string): boolean | undefined {
+ const value = optionalStringContext(app, key);
+ if (value === undefined) {
+ return undefined;
+ }
+ if (value !== 'true' && value !== 'false') {
+ throw new Error(`CDK context '${key}' must be true or false`);
+ }
+ return value === 'true';
+}
+
+// Accepts a JSON object of string values, for example
+// -c sinkProperties='{"sink.batch.max-size":"50000"}'.
+function optionalPropertiesContext(
+ app: cdk.App,
+ key: string,
+): Record | undefined {
+ const value = app.node.tryGetContext(key);
+ if (value === undefined) {
+ return undefined;
+ }
+ let parsed: unknown = value;
+ if (typeof value === 'string') {
+ try {
+ parsed = JSON.parse(value);
+ } catch {
+ throw new Error(`CDK context '${key}' must be a JSON object`);
+ }
+ }
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
+ throw new Error(`CDK context '${key}' must be a JSON object`);
+ }
+ return Object.fromEntries(
+ Object.entries(parsed as Record).map(([name, entry]) => [
+ name,
+ String(entry),
+ ]),
+ );
+}
+
+function applicationJarPath(app: cdk.App): string {
+ const configuredPath = optionalStringContext(app, 'applicationJarPath');
+ if (configuredPath === undefined) {
+ throw new Error(
+ "CDK context 'applicationJarPath' is required; " +
+ "pass '-c applicationJarPath=/absolute/path/to/application-all.jar'",
+ );
+ }
+
+ const resolvedPath = path.resolve(__dirname, '..', configuredPath);
+ if (!fs.existsSync(resolvedPath)) {
+ throw new Error(`Application JAR does not exist: ${resolvedPath}`);
+ }
+ if (!fs.statSync(resolvedPath).isFile()) {
+ throw new Error(`Application JAR path is not a file: ${resolvedPath}`);
+ }
+ if (path.extname(resolvedPath).toLowerCase() !== '.jar') {
+ throw new Error(`Application artifact must be a .jar file: ${resolvedPath}`);
+ }
+ return resolvedPath;
+}
+
+const app = new cdk.App();
+
+new ManagedFlinkExampleStack(app, 'ManagedFlinkInfluxDB3ExampleStack', {
+ env: {
+ account: process.env.CDK_DEFAULT_ACCOUNT,
+ region: process.env.CDK_DEFAULT_REGION,
+ },
+ applicationJarPath: applicationJarPath(app),
+ lifecycleCodePath: path.resolve(
+ __dirname,
+ '../lambda/flink-application-lifecycle',
+ ),
+ applicationName: stringContext(app, 'applicationName', 'influxdb3-flink-example'),
+ databaseName: stringContext(app, 'databaseName', 'sensors'),
+ flinkRuntime: stringContext(app, 'flinkRuntime', 'FLINK-2_3'),
+ pipeline: stringContext(app, 'pipeline', 'datastream'),
+ influxDbEndpoint: optionalStringContext(app, 'influxDbEndpoint'),
+ influxDbSecretArn: optionalStringContext(app, 'influxDbSecretArn'),
+ influxDbTokenField: stringContext(app, 'influxDbTokenField', 'token'),
+ influxDbSecretKmsKeyArn: optionalStringContext(
+ app,
+ 'influxDbSecretKmsKeyArn',
+ ),
+ influxDbClusterName: optionalStringContext(app, 'influxDbClusterName'),
+ parallelism: optionalNumberContext(app, 'parallelism'),
+ parallelismPerKpu: optionalNumberContext(app, 'parallelismPerKpu'),
+ checkpointingEnabled: optionalBooleanContext(app, 'checkpointingEnabled'),
+ checkpointIntervalMillis: optionalNumberContext(app, 'checkpointIntervalMillis'),
+ dataGenProperties: optionalPropertiesContext(app, 'dataGenProperties'),
+ sinkProperties: optionalPropertiesContext(app, 'sinkProperties'),
+ flinkSubnetIds: stringListContext(app, 'flinkSubnetIds'),
+ flinkSecurityGroupIds: stringListContext(app, 'flinkSecurityGroupIds'),
+});
diff --git a/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/infra/cdk.json b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/infra/cdk.json
new file mode 100644
index 00000000..5fab8e22
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/infra/cdk.json
@@ -0,0 +1,114 @@
+{
+ "app": "npx ts-node --prefer-ts-exts bin/app.ts",
+ "progress": "errors-only",
+ "context": {
+ "@aws-cdk/core:checkSecretUsage": true,
+ "@aws-cdk/core:enablePartitionLiterals": true,
+ "@aws-cdk/core:defaultCrossStackReferences": "weak",
+ "@aws-cdk/core:target-partitions": [
+ "aws",
+ "aws-cn"
+ ],
+ "@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": true,
+ "applicationName": "influxdb3-flink-example",
+ "databaseName": "sensors",
+ "flinkRuntime": "FLINK-2_3",
+ "influxDbTokenField": "token",
+ "@aws-cdk/aws-signer:signingProfileNamePassedToCfn": true,
+ "@aws-cdk/core:newStyleStackSynthesis": true,
+ "@aws-cdk/core:stackRelativeExports": true,
+ "@aws-cdk/aws-ecs-patterns:secGroupsDisablesImplicitOpenListener": true,
+ "@aws-cdk/aws-rds:lowercaseDbIdentifier": true,
+ "@aws-cdk/aws-apigateway:usagePlanKeyOrderInsensitiveId": true,
+ "@aws-cdk/aws-lambda:recognizeVersionProps": true,
+ "@aws-cdk/aws-lambda:recognizeLayerVersion": true,
+ "@aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021": true,
+ "@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": true,
+ "@aws-cdk/aws-ecs:arnFormatIncludesClusterName": true,
+ "@aws-cdk/aws-iam:minimizePolicies": true,
+ "@aws-cdk/core:validateSnapshotRemovalPolicy": true,
+ "@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName": true,
+ "@aws-cdk/aws-s3:createDefaultLoggingPolicy": true,
+ "@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption": true,
+ "@aws-cdk/aws-apigateway:disableCloudWatchRole": true,
+ "@aws-cdk/aws-events:eventsTargetQueueSameAccount": true,
+ "@aws-cdk/aws-ecs:disableExplicitDeploymentControllerForCircuitBreaker": true,
+ "@aws-cdk/aws-iam:importedRoleStackSafeDefaultPolicyName": true,
+ "@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": true,
+ "@aws-cdk/aws-route53-patters:useCertificate": true,
+ "@aws-cdk/customresources:installLatestAwsSdkDefault": false,
+ "@aws-cdk/aws-rds:databaseProxyUniqueResourceName": true,
+ "@aws-cdk/aws-codedeploy:removeAlarmsFromDeploymentGroup": true,
+ "@aws-cdk/aws-apigateway:authorizerChangeDeploymentLogicalId": true,
+ "@aws-cdk/aws-ec2:launchTemplateDefaultUserData": true,
+ "@aws-cdk/aws-secretsmanager:useAttachedSecretResourcePolicyForSecretTargetAttachments": true,
+ "@aws-cdk/aws-redshift:columnId": true,
+ "@aws-cdk/aws-stepfunctions-tasks:enableEmrServicePolicyV2": true,
+ "@aws-cdk/aws-ec2:restrictDefaultSecurityGroup": true,
+ "@aws-cdk/aws-apigateway:requestValidatorUniqueId": true,
+ "@aws-cdk/aws-kms:aliasNameRef": true,
+ "@aws-cdk/aws-kms:applyImportedAliasPermissionsToPrincipal": true,
+ "@aws-cdk/aws-autoscaling:generateLaunchTemplateInsteadOfLaunchConfig": true,
+ "@aws-cdk/core:includePrefixInUniqueNameGeneration": true,
+ "@aws-cdk/aws-efs:denyAnonymousAccess": true,
+ "@aws-cdk/aws-opensearchservice:enableOpensearchMultiAzWithStandby": true,
+ "@aws-cdk/aws-lambda-nodejs:useLatestRuntimeVersion": true,
+ "@aws-cdk/aws-efs:mountTargetOrderInsensitiveLogicalId": true,
+ "@aws-cdk/aws-rds:auroraClusterChangeScopeOfInstanceParameterGroupWithEachParameters": true,
+ "@aws-cdk/aws-appsync:useArnForSourceApiAssociationIdentifier": true,
+ "@aws-cdk/aws-rds:preventRenderingDeprecatedCredentials": true,
+ "@aws-cdk/aws-codepipeline-actions:useNewDefaultBranchForCodeCommitSource": true,
+ "@aws-cdk/aws-cloudwatch-actions:changeLambdaPermissionLogicalIdForLambdaAction": true,
+ "@aws-cdk/aws-codepipeline:crossAccountKeysDefaultValueToFalse": true,
+ "@aws-cdk/aws-codepipeline:defaultPipelineTypeToV2": true,
+ "@aws-cdk/aws-kms:reduceCrossAccountRegionPolicyScope": true,
+ "@aws-cdk/pipelines:reduceAssetRoleTrustScope": true,
+ "@aws-cdk/aws-eks:nodegroupNameAttribute": true,
+ "@aws-cdk/aws-eks:useNativeOidcProvider": true,
+ "@aws-cdk/aws-ec2:ebsDefaultGp3Volume": true,
+ "@aws-cdk/aws-ecs:removeDefaultDeploymentAlarm": true,
+ "@aws-cdk/custom-resources:logApiResponseDataPropertyTrueDefault": false,
+ "@aws-cdk/aws-s3:keepNotificationInImportedBucket": false,
+ "@aws-cdk/aws-stepfunctions-tasks:useNewS3UriParametersForBedrockInvokeModelTask": true,
+ "@aws-cdk/core:explicitStackTags": true,
+ "@aws-cdk/aws-ecs:reduceEc2FargateCloudWatchPermissions": true,
+ "@aws-cdk/aws-dynamodb:resourcePolicyPerReplica": true,
+ "@aws-cdk/aws-ec2:ec2SumTImeoutEnabled": true,
+ "@aws-cdk/aws-appsync:appSyncGraphQLAPIScopeLambdaPermission": true,
+ "@aws-cdk/aws-rds:setCorrectValueForDatabaseInstanceReadReplicaInstanceResourceId": true,
+ "@aws-cdk/core:cfnIncludeRejectComplexResourceUpdateCreatePolicyIntrinsics": true,
+ "@aws-cdk/aws-lambda-nodejs:sdkV3ExcludeSmithyPackages": true,
+ "@aws-cdk/aws-stepfunctions-tasks:fixRunEcsTaskPolicy": true,
+ "@aws-cdk/aws-ec2:bastionHostUseAmazonLinux2023ByDefault": true,
+ "@aws-cdk/core:aspectStabilization": true,
+ "@aws-cdk/aws-route53-targets:userPoolDomainNameMethodWithoutCustomResource": true,
+ "@aws-cdk/aws-elasticloadbalancingV2:albDualstackWithoutPublicIpv4SecurityGroupRulesDefault": true,
+ "@aws-cdk/aws-iam:oidcRejectUnauthorizedConnections": true,
+ "@aws-cdk/core:enableAdditionalMetadataCollection": true,
+ "@aws-cdk/aws-lambda:createNewPoliciesWithAddToRolePolicy": false,
+ "@aws-cdk/aws-s3:setUniqueReplicationRoleName": true,
+ "@aws-cdk/pipelines:reduceStageRoleTrustScope": true,
+ "@aws-cdk/aws-events:requireEventBusPolicySid": true,
+ "@aws-cdk/core:aspectPrioritiesMutating": true,
+ "@aws-cdk/aws-dynamodb:retainTableReplica": true,
+ "@aws-cdk/cognito:logUserPoolClientSecretValue": false,
+ "@aws-cdk/pipelines:reduceCrossAccountActionRoleTrustScope": true,
+ "@aws-cdk/aws-stepfunctions:useDistributedMapResultWriterV2": true,
+ "@aws-cdk/s3-notifications:addS3TrustKeyPolicyForSnsSubscriptions": true,
+ "@aws-cdk/aws-ec2:requirePrivateSubnetsForEgressOnlyInternetGateway": true,
+ "@aws-cdk/aws-ec2-alpha:useResourceIdForVpcV2Migration": false,
+ "@aws-cdk/aws-s3:publicAccessBlockedByDefault": true,
+ "@aws-cdk/aws-lambda:useCdkManagedLogGroup": true,
+ "@aws-cdk/aws-elasticloadbalancingv2:networkLoadBalancerWithSecurityGroupByDefault": true,
+ "@aws-cdk/aws-stepfunctions-tasks:httpInvokeDynamicJsonPathEndpoint": true,
+ "@aws-cdk/aws-ecs-patterns:uniqueTargetGroupId": true,
+ "@aws-cdk/aws-route53-patterns:useDistribution": true,
+ "@aws-cdk/aws-cloudfront:defaultFunctionRuntimeV2_0": true,
+ "@aws-cdk/aws-elasticloadbalancingv2:usePostQuantumTlsPolicy": true,
+ "@aws-cdk/core:automaticL1Traits": true,
+ "@aws-cdk/aws-batch:defaultToAL2023": true,
+ "@aws-cdk/aws-eks:defaultToAL2023": true,
+ "@aws-cdk/core:annotationsInValidationReport": true,
+ "@aws-cdk/core:validateAgainstDefaultRules": true
+ }
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/infra/lambda/flink-application-lifecycle/handler.py b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/infra/lambda/flink-application-lifecycle/handler.py
new file mode 100644
index 00000000..3c4495b8
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/infra/lambda/flink-application-lifecycle/handler.py
@@ -0,0 +1,250 @@
+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+import logging
+
+import boto3
+
+
+_LOGGER = logging.getLogger(__name__)
+_CLIENT = boto3.client("kinesisanalyticsv2")
+_TRANSITIONAL_STATES = {
+ "AUTOSCALING",
+ "FORCE_STOPPING",
+ "MAINTENANCE",
+ "ROLLING_BACK",
+ "STARTING",
+ "STOPPING",
+ "UPDATING",
+}
+_FAILED_OPERATION_STATES = {"CANCELLED", "FAILED"}
+_MAX_OPERATION_ERROR_LENGTH = 1200
+
+
+def _application_status(application_name):
+ try:
+ response = _CLIENT.describe_application(
+ ApplicationName=application_name,
+ IncludeAdditionalDetails=False,
+ )
+ except _CLIENT.exceptions.ResourceNotFoundException:
+ return None
+ return response["ApplicationDetail"]["ApplicationStatus"]
+
+
+def _in_progress_operation_id(application_name, operation_name):
+ response = _CLIENT.list_application_operations(
+ ApplicationName=application_name,
+ Limit=1,
+ Operation=operation_name,
+ OperationStatus="IN_PROGRESS",
+ )
+ operations = response.get("ApplicationOperationInfoList") or []
+ if not operations:
+ return None
+ return operations[0].get("OperationId")
+
+
+def _request_start(application_name, status):
+ if status == "RUNNING":
+ return None
+ if status == "STARTING":
+ operation_id = _in_progress_operation_id(
+ application_name,
+ "StartApplication",
+ )
+ if operation_id:
+ return operation_id
+ raise RuntimeError(
+ f"Managed Flink application '{application_name}' is STARTING, "
+ "but no in-progress start operation could be found"
+ )
+ if status != "READY":
+ raise RuntimeError(
+ f"Cannot start Managed Flink application '{application_name}' "
+ f"from status '{status}'"
+ )
+ try:
+ response = _CLIENT.start_application(
+ ApplicationName=application_name,
+ RunConfiguration={
+ "ApplicationRestoreConfiguration": {
+ "ApplicationRestoreType": "SKIP_RESTORE_FROM_SNAPSHOT"
+ },
+ "FlinkRunConfiguration": {
+ "AllowNonRestoredState": True,
+ },
+ },
+ )
+ except _CLIENT.exceptions.ResourceInUseException as error:
+ operation_id = _in_progress_operation_id(
+ application_name,
+ "StartApplication",
+ )
+ if operation_id:
+ return operation_id
+ raise RuntimeError(
+ f"Managed Flink application '{application_name}' rejected "
+ "StartApplication as already in use, but no in-progress start "
+ "operation could be found"
+ ) from error
+ operation_id = response.get("OperationId")
+ if not operation_id:
+ raise RuntimeError(
+ f"StartApplication for Managed Flink application "
+ f"'{application_name}' did not return an operation ID"
+ )
+ return operation_id
+
+
+def _request_stop(application_name, status):
+ if status != "RUNNING":
+ return None
+ try:
+ response = _CLIENT.stop_application(ApplicationName=application_name)
+ except _CLIENT.exceptions.ResourceInUseException:
+ return None
+ operation_id = response.get("OperationId")
+ if not operation_id:
+ raise RuntimeError(
+ f"StopApplication for Managed Flink application "
+ f"'{application_name}' did not return an operation ID"
+ )
+ return operation_id
+
+
+def _operation_details(application_name, operation_id):
+ try:
+ response = _CLIENT.describe_application_operation(
+ ApplicationName=application_name,
+ OperationId=operation_id,
+ )
+ except _CLIENT.exceptions.ResourceNotFoundException:
+ return None
+ return response["ApplicationOperationInfoDetails"]
+
+
+def _summarize_operation_error(error):
+ normalized = " ".join((error or "No failure details were returned").split())
+ if len(normalized) <= _MAX_OPERATION_ERROR_LENGTH:
+ return normalized
+
+ separator = " ... "
+ head_length = (_MAX_OPERATION_ERROR_LENGTH - len(separator)) // 2
+ tail_length = _MAX_OPERATION_ERROR_LENGTH - len(separator) - head_length
+ return normalized[:head_length] + separator + normalized[-tail_length:]
+
+
+def _operation_status(
+ application_name,
+ operation_id,
+ operation_name,
+ raise_on_failure=True,
+):
+ details = _operation_details(application_name, operation_id)
+ if details is None:
+ return None
+
+ status = details["OperationStatus"]
+ if status in _FAILED_OPERATION_STATES:
+ failure_details = details.get("OperationFailureDetails") or {}
+ error_info = failure_details.get("ErrorInfo") or {}
+ error = _summarize_operation_error(error_info.get("ErrorString"))
+ message = (
+ f"{operation_name} operation '{operation_id}' {status.lower()} "
+ f"for Managed Flink application '{application_name}': {error}"
+ )
+ if raise_on_failure:
+ raise RuntimeError(message)
+ _LOGGER.warning("%s; continuing CloudFormation deletion", message)
+ return status
+
+
+def on_event(event, _context):
+ application_name = event["ResourceProperties"]["ApplicationName"]
+ request_type = event["RequestType"]
+ status = _application_status(application_name)
+ operation_id = None
+ operation_name = None
+
+ if request_type == "Delete":
+ operation_id = _request_stop(application_name, status)
+ operation_name = "StopApplication"
+ else:
+ if status is None:
+ raise RuntimeError(
+ f"Managed Flink application '{application_name}' was not found"
+ )
+ operation_id = _request_start(application_name, status)
+ operation_name = "StartApplication"
+
+ response = {
+ "PhysicalResourceId": event.get("PhysicalResourceId", application_name),
+ "Data": {
+ "ObservedStatus": status or "NOT_FOUND",
+ },
+ }
+ if operation_id:
+ response["LifecycleOperationId"] = operation_id
+ response["LifecycleOperation"] = operation_name
+ return response
+
+
+def is_complete(event, _context):
+ application_name = event["ResourceProperties"]["ApplicationName"]
+ request_type = event["RequestType"]
+ status = _application_status(application_name)
+ operation_id = event.get("LifecycleOperationId")
+ operation_name = event.get("LifecycleOperation", "Lifecycle")
+
+ if request_type == "Delete":
+ if status is None or status == "READY":
+ return {"IsComplete": True}
+ operation_status = None
+ if operation_id:
+ operation_status = _operation_status(
+ application_name,
+ operation_id,
+ operation_name,
+ raise_on_failure=False,
+ )
+ if operation_status in _FAILED_OPERATION_STATES:
+ # Application deletion also halts execution, so a failed best-effort
+ # stop must not strand the stack in DELETE_FAILED.
+ return {"IsComplete": True}
+ if status in _TRANSITIONAL_STATES or status == "RUNNING":
+ if status == "RUNNING" and operation_status is None:
+ _request_stop(application_name, status)
+ return {"IsComplete": False}
+ return {"IsComplete": True}
+
+ if status == "RUNNING":
+ return {"IsComplete": True}
+ if status is None:
+ raise RuntimeError(
+ f"Managed Flink application '{application_name}' was deleted "
+ "while waiting for RUNNING"
+ )
+
+ operation_status = None
+ if operation_id:
+ operation_status = _operation_status(
+ application_name,
+ operation_id,
+ operation_name,
+ )
+ if status in _TRANSITIONAL_STATES:
+ return {"IsComplete": False}
+ if status == "READY":
+ if operation_id and operation_status in {None, "IN_PROGRESS"}:
+ return {"IsComplete": False}
+ # Failed operations were raised above. A successful start that leaves
+ # the application READY is no longer progressing toward RUNNING.
+ raise RuntimeError(
+ f"Managed Flink application '{application_name}' returned to READY "
+ "before reaching RUNNING"
+ )
+ raise RuntimeError(
+ f"Cannot start Managed Flink application '{application_name}' "
+ f"from status '{status}'"
+ )
diff --git a/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/infra/lib/flink-application-lifecycle.ts b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/infra/lib/flink-application-lifecycle.ts
new file mode 100644
index 00000000..f7df0cbd
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/infra/lib/flink-application-lifecycle.ts
@@ -0,0 +1,96 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ */
+
+import * as cdk from 'aws-cdk-lib';
+import * as iam from 'aws-cdk-lib/aws-iam';
+import * as lambda from 'aws-cdk-lib/aws-lambda';
+import * as logs from 'aws-cdk-lib/aws-logs';
+import * as cr from 'aws-cdk-lib/custom-resources';
+import { Construct } from 'constructs';
+
+export interface FlinkApplicationLifecycleProps {
+ readonly applicationArn: string;
+ readonly applicationName: string;
+ readonly codePath: string;
+ readonly deploymentFingerprint: string;
+}
+
+/**
+ * Starts a Managed Flink application after CloudFormation creates it and
+ * attempts to stop it before deletion. Stop failures are logged without
+ * blocking teardown because application deletion also halts execution.
+ */
+export class FlinkApplicationLifecycle extends Construct {
+ public readonly resource: cdk.CustomResource;
+
+ public constructor(
+ scope: Construct,
+ id: string,
+ props: FlinkApplicationLifecycleProps,
+ ) {
+ super(scope, id);
+
+ const onEventLogGroup = new logs.LogGroup(this, 'OnEventLogGroup', {
+ retention: logs.RetentionDays.ONE_WEEK,
+ removalPolicy: cdk.RemovalPolicy.DESTROY,
+ });
+ const onEvent = new lambda.Function(this, 'OnEvent', {
+ runtime: lambda.Runtime.PYTHON_3_12,
+ handler: 'handler.on_event',
+ code: lambda.Code.fromAsset(props.codePath),
+ timeout: cdk.Duration.minutes(2),
+ logGroup: onEventLogGroup,
+ description: 'Requests Managed Flink application start and stop transitions',
+ });
+
+ const isCompleteLogGroup = new logs.LogGroup(this, 'IsCompleteLogGroup', {
+ retention: logs.RetentionDays.ONE_WEEK,
+ removalPolicy: cdk.RemovalPolicy.DESTROY,
+ });
+ const isComplete = new lambda.Function(this, 'IsComplete', {
+ runtime: lambda.Runtime.PYTHON_3_12,
+ handler: 'handler.is_complete',
+ code: lambda.Code.fromAsset(props.codePath),
+ timeout: cdk.Duration.minutes(2),
+ logGroup: isCompleteLogGroup,
+ description: 'Waits for Managed Flink application lifecycle transitions',
+ });
+
+ const applicationLifecyclePolicy = new iam.PolicyStatement({
+ actions: [
+ 'kinesisanalytics:DescribeApplication',
+ 'kinesisanalytics:DescribeApplicationOperation',
+ 'kinesisanalytics:ListApplicationOperations',
+ 'kinesisanalytics:StartApplication',
+ 'kinesisanalytics:StopApplication',
+ ],
+ resources: [props.applicationArn],
+ });
+ onEvent.addToRolePolicy(applicationLifecyclePolicy);
+ isComplete.addToRolePolicy(applicationLifecyclePolicy);
+
+ const providerLogGroup = new logs.LogGroup(this, 'ProviderLogGroup', {
+ retention: logs.RetentionDays.ONE_WEEK,
+ removalPolicy: cdk.RemovalPolicy.DESTROY,
+ });
+ const provider = new cr.Provider(this, 'Provider', {
+ onEventHandler: onEvent,
+ isCompleteHandler: isComplete,
+ queryInterval: cdk.Duration.seconds(20),
+ totalTimeout: cdk.Duration.minutes(45),
+ logGroup: providerLogGroup,
+ });
+
+ this.resource = new cdk.CustomResource(this, 'Resource', {
+ serviceToken: provider.serviceToken,
+ serviceTimeout: cdk.Duration.minutes(55),
+ resourceType: 'Custom::FlinkApplicationLifecycle',
+ properties: {
+ ApplicationName: props.applicationName,
+ DeploymentFingerprint: props.deploymentFingerprint,
+ },
+ });
+ }
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/infra/lib/managed-flink-example-stack.ts b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/infra/lib/managed-flink-example-stack.ts
new file mode 100644
index 00000000..fabbb0a6
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/infra/lib/managed-flink-example-stack.ts
@@ -0,0 +1,450 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ */
+
+import * as cdk from 'aws-cdk-lib';
+import * as iam from 'aws-cdk-lib/aws-iam';
+import * as kinesis from 'aws-cdk-lib/aws-kinesis';
+import * as kinesisanalytics from 'aws-cdk-lib/aws-kinesisanalyticsv2';
+import * as logs from 'aws-cdk-lib/aws-logs';
+import * as s3assets from 'aws-cdk-lib/aws-s3-assets';
+import { Construct } from 'constructs';
+import { FlinkApplicationLifecycle } from './flink-application-lifecycle';
+import { FLINK_METRICS_LEVEL, SinkMonitoring } from './sink-monitoring';
+
+const INFLUX_DB_ENDPOINT_PATTERN =
+ '^https://(?:\\[[0-9A-Fa-f:]+\\]|[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)*)' +
+ '(?::[0-9]{1,5})?/?$';
+
+export type ApplicationPipeline = 'datastream' | 'sql' | 'datagen';
+
+const APPLICATION_PIPELINES: readonly ApplicationPipeline[] = [
+ 'datastream',
+ 'sql',
+ 'datagen',
+];
+
+// Managed Flink accepts 1 to 8 parallel tasks per KPU.
+const MAX_PARALLELISM_PER_KPU = 8;
+const DEFAULT_CHECKPOINT_INTERVAL_MILLIS = 60_000;
+
+export interface ManagedFlinkExampleStackProps extends cdk.StackProps {
+ readonly applicationJarPath: string;
+ readonly lifecycleCodePath: string;
+ readonly applicationName?: string;
+ readonly databaseName?: string;
+ readonly flinkRuntime?: string;
+ readonly pipeline?: string;
+ readonly influxDbEndpoint?: string;
+ readonly influxDbSecretArn?: string;
+ readonly influxDbTokenField?: string;
+ readonly influxDbSecretKmsKeyArn?: string;
+ readonly influxDbClusterName?: string;
+ /** Application parallelism; defaults to 1. */
+ readonly parallelism?: number;
+ /** Parallel tasks per KPU, from 1 to 8; defaults to 1. */
+ readonly parallelismPerKpu?: number;
+ /** Enables checkpointing; defaults to true. */
+ readonly checkpointingEnabled?: boolean;
+ /** Checkpoint interval when checkpointing is enabled; defaults to 60,000 ms. */
+ readonly checkpointIntervalMillis?: number;
+ /** `DataGen` runtime properties for the datagen pipeline. */
+ readonly dataGenProperties?: Record;
+ /** `Sink` runtime properties that tune the connector. */
+ readonly sinkProperties?: Record;
+ readonly flinkSubnetIds?: string[];
+ readonly flinkSecurityGroupIds?: string[];
+}
+
+export class ManagedFlinkExampleStack extends cdk.Stack {
+ public constructor(
+ scope: Construct,
+ id: string,
+ props: ManagedFlinkExampleStackProps,
+ ) {
+ super(scope, id, props);
+
+ const applicationName = props.applicationName ?? 'influxdb3-flink-example';
+ const databaseName = props.databaseName ?? 'sensors';
+ const flinkRuntime = props.flinkRuntime ?? 'FLINK-2_3';
+ const influxDbTokenField = props.influxDbTokenField ?? 'token';
+ // Matches the application, which parses the pipeline case-insensitively.
+ const pipeline = (props.pipeline ?? 'datastream').toLowerCase();
+ if (!APPLICATION_PIPELINES.includes(pipeline as ApplicationPipeline)) {
+ throw new Error(
+ `pipeline must be one of ${APPLICATION_PIPELINES.join(', ')}`,
+ );
+ }
+ const parallelism = props.parallelism ?? 1;
+ const parallelismPerKpu = props.parallelismPerKpu ?? 1;
+ const checkpointingEnabled = props.checkpointingEnabled ?? true;
+ const checkpointIntervalMillis =
+ props.checkpointIntervalMillis ?? DEFAULT_CHECKPOINT_INTERVAL_MILLIS;
+ requireInteger(parallelism, 'parallelism', 1);
+ requireInteger(parallelismPerKpu, 'parallelismPerKpu', 1, MAX_PARALLELISM_PER_KPU);
+ requireInteger(checkpointIntervalMillis, 'checkpointIntervalMillis', 1);
+ if (props.dataGenProperties !== undefined && pipeline !== 'datagen') {
+ throw new Error('dataGenProperties requires the datagen pipeline');
+ }
+ const readsKinesis = pipeline !== 'datagen';
+ if (
+ !cdk.Token.isUnresolved(databaseName) &&
+ !/^[A-Za-z0-9_-]+$/.test(databaseName)
+ ) {
+ throw new Error(
+ 'databaseName must contain only letters, numbers, hyphens, and underscores',
+ );
+ }
+ if (
+ !cdk.Token.isUnresolved(influxDbTokenField) &&
+ influxDbTokenField.trim().length === 0
+ ) {
+ throw new Error('influxDbTokenField must not be blank');
+ }
+ if (
+ props.influxDbEndpoint !== undefined &&
+ !cdk.Token.isUnresolved(props.influxDbEndpoint) &&
+ !new RegExp(INFLUX_DB_ENDPOINT_PATTERN).test(props.influxDbEndpoint)
+ ) {
+ throw new Error(
+ 'influxDbEndpoint must be an HTTPS base URL with a valid host, ' +
+ 'an optional port, and no API path',
+ );
+ }
+
+ const endpoint =
+ props.influxDbEndpoint ??
+ new cdk.CfnParameter(this, 'InfluxDbEndpoint', {
+ type: 'String',
+ description:
+ 'Existing InfluxDB base endpoint including scheme and port, without an API path',
+ allowedPattern: INFLUX_DB_ENDPOINT_PATTERN,
+ constraintDescription:
+ 'must be an HTTPS base URL with a valid host, an optional port, and no API path',
+ }).valueAsString;
+ const secretArnParameter =
+ props.influxDbSecretArn === undefined
+ ? new cdk.CfnParameter(this, 'InfluxDbSecretArn', {
+ type: 'String',
+ description:
+ 'Secrets Manager ARN containing the InfluxDB authentication token',
+ allowedPattern:
+ 'arn:[^:]+:secretsmanager:[^:]+:[0-9]{12}:secret:.+',
+ })
+ : undefined;
+ const secretArn =
+ props.influxDbSecretArn ?? secretArnParameter!.valueAsString;
+ const secretRegion = cdk.Fn.select(3, cdk.Fn.split(':', secretArn));
+
+ const subnetIds = props.flinkSubnetIds;
+ const securityGroupIds = props.flinkSecurityGroupIds;
+ const hasSubnetIds = subnetIds !== undefined && subnetIds.length > 0;
+ const hasSecurityGroupIds =
+ securityGroupIds !== undefined && securityGroupIds.length > 0;
+ if (hasSubnetIds !== hasSecurityGroupIds) {
+ throw new Error(
+ 'flinkSubnetIds and flinkSecurityGroupIds must be provided together',
+ );
+ }
+
+ // The datagen pipeline generates its input, so it has no stream.
+ let inputStream: kinesis.Stream | undefined;
+ if (readsKinesis) {
+ inputStream = new kinesis.Stream(this, 'InputStream', {
+ streamMode: kinesis.StreamMode.ON_DEMAND,
+ encryption: kinesis.StreamEncryption.MANAGED,
+ });
+ inputStream.applyRemovalPolicy(cdk.RemovalPolicy.DESTROY);
+ }
+
+ const applicationArtifact = new s3assets.Asset(this, 'ApplicationArtifact', {
+ path: props.applicationJarPath,
+ });
+
+ const executionRole = new iam.Role(this, 'FlinkExecutionRole', {
+ assumedBy: new iam.ServicePrincipal('kinesisanalytics.amazonaws.com'),
+ description: 'Execution role for the InfluxDB 3 Managed Flink example application',
+ });
+ executionRole.addToPolicy(
+ new iam.PolicyStatement({
+ actions: ['s3:GetObject', 's3:GetObjectVersion'],
+ resources: [
+ applicationArtifact.bucket.arnForObjects(applicationArtifact.s3ObjectKey),
+ ],
+ }),
+ );
+ inputStream?.grantRead(executionRole);
+ executionRole.addToPolicy(
+ new iam.PolicyStatement({
+ actions: ['secretsmanager:GetSecretValue'],
+ // The second form matches the random suffix when secretArn omits it.
+ resources: [secretArn, `${secretArn}-??????`],
+ }),
+ );
+ if (props.influxDbSecretKmsKeyArn !== undefined) {
+ executionRole.addToPolicy(
+ new iam.PolicyStatement({
+ actions: ['kms:Decrypt'],
+ resources: [props.influxDbSecretKmsKeyArn],
+ }),
+ );
+ }
+ if (hasSubnetIds && hasSecurityGroupIds) {
+ executionRole.addToPolicy(
+ new iam.PolicyStatement({
+ actions: [
+ 'ec2:CreateNetworkInterface',
+ 'ec2:CreateNetworkInterfacePermission',
+ 'ec2:DeleteNetworkInterface',
+ 'ec2:DescribeDhcpOptions',
+ 'ec2:DescribeNetworkInterfaces',
+ 'ec2:DescribeSecurityGroups',
+ 'ec2:DescribeSubnets',
+ 'ec2:DescribeVpcs',
+ ],
+ resources: ['*'],
+ }),
+ );
+ }
+
+ const applicationLogGroup = new logs.LogGroup(this, 'ApplicationLogGroup', {
+ logGroupName: `/aws/kinesis-analytics/${applicationName}`,
+ retention: logs.RetentionDays.ONE_WEEK,
+ removalPolicy: cdk.RemovalPolicy.DESTROY,
+ });
+ const applicationLogStream = new logs.LogStream(this, 'ApplicationLogStream', {
+ logGroup: applicationLogGroup,
+ logStreamName: 'application',
+ removalPolicy: cdk.RemovalPolicy.DESTROY,
+ });
+ const applicationLogStreamArn = this.formatArn({
+ service: 'logs',
+ resource: 'log-group',
+ resourceName:
+ `${applicationLogGroup.logGroupName}:log-stream:` +
+ applicationLogStream.logStreamName,
+ arnFormat: cdk.ArnFormat.COLON_RESOURCE_NAME,
+ });
+ executionRole.addToPolicy(
+ new iam.PolicyStatement({
+ actions: ['logs:DescribeLogGroups'],
+ resources: ['*'],
+ }),
+ );
+ executionRole.addToPolicy(
+ new iam.PolicyStatement({
+ actions: ['logs:DescribeLogStreams'],
+ resources: [applicationLogGroup.logGroupArn],
+ }),
+ );
+ executionRole.addToPolicy(
+ new iam.PolicyStatement({
+ actions: ['logs:PutLogEvents'],
+ resources: [applicationLogStreamArn],
+ }),
+ );
+
+ const application = new kinesisanalytics.CfnApplication(
+ this,
+ 'FlinkApplication',
+ {
+ applicationName,
+ applicationDescription:
+ readsKinesis
+ ? 'Kinesis to an existing InfluxDB 3 endpoint example application'
+ : 'Generated load to an existing InfluxDB 3 endpoint',
+ applicationMode: 'STREAMING',
+ runtimeEnvironment: flinkRuntime,
+ serviceExecutionRole: executionRole.roleArn,
+ runConfiguration: {
+ applicationRestoreConfiguration: {
+ applicationRestoreType: 'SKIP_RESTORE_FROM_SNAPSHOT',
+ },
+ flinkRunConfiguration: {
+ allowNonRestoredState: true,
+ },
+ },
+ applicationConfiguration: {
+ applicationCodeConfiguration: {
+ codeContentType: 'ZIPFILE',
+ codeContent: {
+ s3ContentLocation: {
+ bucketArn: applicationArtifact.bucket.bucketArn,
+ fileKey: applicationArtifact.s3ObjectKey,
+ },
+ },
+ },
+ applicationSnapshotConfiguration: {
+ snapshotsEnabled: false,
+ },
+ environmentProperties: {
+ propertyGroups: [
+ {
+ propertyGroupId: 'Application',
+ propertyMap: {
+ pipeline,
+ },
+ },
+ ...(inputStream !== undefined
+ ? [
+ {
+ propertyGroupId: 'KinesisSource',
+ propertyMap: {
+ streamArn: inputStream.streamArn,
+ region: this.region,
+ initialPosition: 'LATEST',
+ },
+ },
+ ]
+ : []),
+ {
+ propertyGroupId: 'InfluxDB3',
+ propertyMap: {
+ endpoint,
+ database: databaseName,
+ secretId: secretArn,
+ secretJsonField: influxDbTokenField,
+ region: secretRegion,
+ },
+ },
+ ...optionalPropertyGroup('DataGen', props.dataGenProperties),
+ ...optionalPropertyGroup('Sink', props.sinkProperties),
+ ],
+ },
+ flinkApplicationConfiguration: {
+ checkpointConfiguration: checkpointingEnabled
+ ? {
+ configurationType: 'CUSTOM',
+ checkpointingEnabled: true,
+ checkpointInterval: checkpointIntervalMillis,
+ }
+ : {
+ configurationType: 'CUSTOM',
+ checkpointingEnabled: false,
+ },
+ monitoringConfiguration: {
+ configurationType: 'CUSTOM',
+ logLevel: 'INFO',
+ metricsLevel: FLINK_METRICS_LEVEL,
+ },
+ parallelismConfiguration: {
+ configurationType: 'CUSTOM',
+ autoScalingEnabled: false,
+ parallelism,
+ parallelismPerKpu,
+ },
+ },
+ ...(hasSubnetIds && hasSecurityGroupIds
+ ? {
+ vpcConfigurations: [
+ {
+ securityGroupIds,
+ subnetIds,
+ },
+ ],
+ }
+ : {}),
+ },
+ },
+ );
+ application.node.addDependency(executionRole);
+
+ const loggingOption =
+ new kinesisanalytics.CfnApplicationCloudWatchLoggingOption(
+ this,
+ 'FlinkApplicationLogging',
+ {
+ applicationName: application.ref,
+ cloudWatchLoggingOption: {
+ logStreamArn: applicationLogStreamArn,
+ },
+ },
+ );
+
+ const fingerprintParts = [
+ applicationArtifact.assetHash,
+ flinkRuntime,
+ databaseName,
+ endpoint,
+ secretArn,
+ ...(inputStream !== undefined ? [inputStream.streamArn] : []),
+ pipeline,
+ String(parallelism),
+ String(parallelismPerKpu),
+ String(checkpointingEnabled),
+ String(checkpointIntervalMillis),
+ JSON.stringify(props.dataGenProperties ?? {}),
+ JSON.stringify(props.sinkProperties ?? {}),
+ ...(subnetIds ?? []),
+ ...(securityGroupIds ?? []),
+ ];
+ const lifecycle = new FlinkApplicationLifecycle(
+ this,
+ 'FlinkApplicationLifecycle',
+ {
+ applicationArn: kinesisanalytics.CfnApplication.arnForApplication(
+ application,
+ ),
+ applicationName: application.ref,
+ codePath: props.lifecycleCodePath,
+ deploymentFingerprint: cdk.Fn.join(':', fingerprintParts),
+ },
+ );
+ lifecycle.resource.node.addDependency(loggingOption);
+
+ const monitoring = new SinkMonitoring(this, 'SinkMonitoring', {
+ applicationName: application.ref,
+ influxDbClusterName: props.influxDbClusterName,
+ });
+
+ new cdk.CfnOutput(this, 'ApplicationName', {
+ value: application.ref,
+ });
+ if (inputStream !== undefined) {
+ new cdk.CfnOutput(this, 'KinesisStreamName', {
+ value: inputStream.streamName,
+ });
+ }
+ new cdk.CfnOutput(this, 'InfluxDBEndpoint', {
+ value: endpoint,
+ });
+ new cdk.CfnOutput(this, 'InfluxDBAuthSecretArn', {
+ value: secretArn,
+ });
+ new cdk.CfnOutput(this, 'InfluxDBDatabase', {
+ value: databaseName,
+ });
+ new cdk.CfnOutput(this, 'SinkDashboardName', {
+ value: monitoring.dashboard.dashboardName,
+ });
+ new cdk.CfnOutput(this, 'DroppedRecordsAlarmName', {
+ value: monitoring.droppedRecordsAlarm.alarmName,
+ });
+ }
+}
+
+function requireInteger(
+ value: number,
+ name: string,
+ minimum: number,
+ maximum: number = Number.MAX_SAFE_INTEGER,
+): void {
+ if (!Number.isInteger(value) || value < minimum || value > maximum) {
+ throw new Error(
+ maximum === Number.MAX_SAFE_INTEGER
+ ? `${name} must be an integer of at least ${minimum}`
+ : `${name} must be an integer from ${minimum} to ${maximum}`,
+ );
+ }
+}
+
+function optionalPropertyGroup(
+ propertyGroupId: string,
+ propertyMap: Record | undefined,
+): kinesisanalytics.CfnApplication.PropertyGroupProperty[] {
+ if (propertyMap === undefined || Object.keys(propertyMap).length === 0) {
+ return [];
+ }
+ return [{ propertyGroupId, propertyMap }];
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/infra/lib/sink-monitoring.ts b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/infra/lib/sink-monitoring.ts
new file mode 100644
index 00000000..987ac73b
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/infra/lib/sink-monitoring.ts
@@ -0,0 +1,330 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ */
+
+import * as cdk from 'aws-cdk-lib';
+import * as cloudwatch from 'aws-cdk-lib/aws-cloudwatch';
+import { Construct } from 'constructs';
+
+/**
+ * Managed Flink metrics level used by the application.
+ *
+ * The metrics level decides which dimensions Managed Flink adds to published
+ * metrics. The dashboard and alarm below match the APPLICATION level only, so
+ * the application configuration reads this value instead of repeating it.
+ */
+export const FLINK_METRICS_LEVEL = 'APPLICATION';
+
+const NAMESPACE = 'AWS/KinesisAnalytics';
+const CONNECTOR_DIMENSION = { Connector: 'TimestreamInfluxDB3' };
+const PERIOD = cdk.Duration.minutes(1);
+
+export interface SinkMonitoringProps {
+ readonly applicationName: string;
+ /** Timestream for InfluxDB 3 cluster name; adds a cluster health panel when set. */
+ readonly influxDbClusterName?: string;
+}
+
+/** CloudWatch alarm and dashboard for the InfluxDB 3 sink of one application. */
+export class SinkMonitoring extends Construct {
+ public readonly droppedRecordsAlarm: cloudwatch.Alarm;
+ public readonly dashboard: cloudwatch.Dashboard;
+
+ public constructor(scope: Construct, id: string, props: SinkMonitoringProps) {
+ super(scope, id);
+
+ const application = { Application: props.applicationName };
+ const sinkMetric = (
+ metricName: string,
+ statistic: string,
+ label?: string,
+ ): cloudwatch.Metric =>
+ new cloudwatch.Metric({
+ namespace: NAMESPACE,
+ metricName,
+ dimensionsMap: { ...application, ...CONNECTOR_DIMENSION },
+ statistic,
+ period: PERIOD,
+ label,
+ });
+ const applicationMetric = (
+ metricName: string,
+ statistic: string,
+ label?: string,
+ ): cloudwatch.Metric =>
+ new cloudwatch.Metric({
+ namespace: NAMESPACE,
+ metricName,
+ dimensionsMap: application,
+ statistic,
+ period: PERIOD,
+ label,
+ });
+
+ // Each subtask publishes its own data point every reporting interval, so a
+ // Sum over one period adds every report from every subtask. Dividing by
+ // the number of reports of the job-level uptime metric in the same period
+ // gives the job-wide value regardless of parallelism or report interval.
+ const reportsPerPeriod = applicationMetric('uptime', 'SampleCount');
+ const jobTotal = (
+ metric: cloudwatch.Metric,
+ label: string,
+ ): cloudwatch.MathExpression =>
+ new cloudwatch.MathExpression({
+ expression: `${metric.metricName} / reports`,
+ usingMetrics: { [metric.metricName]: metric, reports: reportsPerPeriod },
+ label,
+ period: PERIOD,
+ });
+
+ // The alarm uses the raw Sum: its zero threshold does not depend on how
+ // many reports the Sum covers.
+ const droppedPerSecond = sinkMetric('numRecordsDroppedPerSecond', 'Sum');
+
+ this.droppedRecordsAlarm = new cloudwatch.Alarm(
+ this,
+ 'DroppedRecordsAlarm',
+ {
+ alarmDescription:
+ 'The InfluxDB 3 sink dropped records under its failure policy. ' +
+ 'Check the application log for the rejected lines.',
+ metric: droppedPerSecond,
+ threshold: 0,
+ comparisonOperator:
+ cloudwatch.ComparisonOperator.GREATER_THAN_THRESHOLD,
+ evaluationPeriods: 1,
+ // No data means the application is stopped or has not written yet.
+ treatMissingData: cloudwatch.TreatMissingData.NOT_BREACHING,
+ },
+ );
+
+ this.dashboard = new cloudwatch.Dashboard(this, 'Dashboard', {
+ dashboardName: `${props.applicationName}-influxdb3-sink`,
+ defaultInterval: cdk.Duration.hours(3),
+ });
+ this.dashboard.addWidgets(
+ new cloudwatch.GraphWidget({
+ title: 'Throughput',
+ left: [
+ jobTotal(
+ sinkMetric('numRecordsWrittenPerSecond', 'Sum'),
+ 'Written records/s',
+ ),
+ jobTotal(
+ applicationMetric('numRecordsInPerSecond', 'Sum'),
+ 'Application input records/s',
+ ),
+ ],
+ width: 12,
+ }),
+ new cloudwatch.GraphWidget({
+ title: 'Write latency (ms)',
+ left: [
+ sinkMetric('writeLatencyP50Millis', 'Average', 'p50'),
+ sinkMetric('writeLatencyP95Millis', 'Maximum', 'p95'),
+ sinkMetric('writeLatencyP99Millis', 'Maximum', 'p99'),
+ ],
+ width: 12,
+ }),
+ );
+ this.dashboard.addWidgets(
+ new cloudwatch.GraphWidget({
+ title: 'Dropped records and failures',
+ left: [
+ jobTotal(droppedPerSecond, 'Dropped records/s'),
+ jobTotal(
+ sinkMetric('numRecordsSendErrorsPerSecond', 'Sum'),
+ 'Send errors/s',
+ ),
+ jobTotal(
+ sinkMetric('numBatchesFailedPerSecond', 'Sum'),
+ 'Failed batches/s',
+ ),
+ ],
+ leftAnnotations: [
+ { value: 0, label: 'Dropped records alarm threshold' },
+ ],
+ width: 12,
+ }),
+ new cloudwatch.GraphWidget({
+ title: 'Throttling and retries',
+ left: [
+ jobTotal(
+ sinkMetric('numThrottledRequests', 'Sum'),
+ 'Throttled requests since job start',
+ ),
+ jobTotal(
+ sinkMetric('numRetries', 'Sum'),
+ 'Retried records since job start',
+ ),
+ jobTotal(
+ sinkMetric('numWriteTimeouts', 'Sum'),
+ 'Write timeouts since job start',
+ ),
+ ],
+ right: [
+ jobTotal(
+ sinkMetric('numRetryDelayMillis', 'Sum'),
+ 'Retry delay since job start (ms)',
+ ),
+ sinkMetric('maxRetryAfterMillis', 'Maximum', 'Largest Retry-After (ms)'),
+ ],
+ width: 12,
+ }),
+ );
+ this.dashboard.addWidgets(
+ new cloudwatch.GraphWidget({
+ title: 'Buffered bytes and in-flight requests',
+ left: [sinkMetric('numBufferedBytes', 'Maximum', 'Buffered bytes')],
+ right: [
+ sinkMetric(
+ 'numInFlightWriteRequests',
+ 'Maximum',
+ 'In-flight write requests',
+ ),
+ ],
+ width: 12,
+ }),
+ new cloudwatch.GraphWidget({
+ title: 'Job health',
+ left: [
+ applicationMetric('heapMemoryUtilization', 'Maximum', 'Heap %'),
+ applicationMetric('cpuUtilization', 'Maximum', 'CPU %'),
+ // The source and sink run as one chained task, so a slow sink shows
+ // as busy time rather than backpressure, which stays at zero.
+ new cloudwatch.MathExpression({
+ expression: 'busyTime / 10',
+ usingMetrics: {
+ busyTime: applicationMetric('busyTimeMsPerSecond', 'Maximum'),
+ },
+ label: 'Busiest task busy %',
+ period: PERIOD,
+ }),
+ ],
+ right: [
+ applicationMetric('numRestarts', 'Maximum', 'Restarts'),
+ applicationMetric(
+ 'numberOfFailedCheckpoints',
+ 'Maximum',
+ 'Failed checkpoints',
+ ),
+ ],
+ width: 12,
+ }),
+ );
+ this.dashboard.addWidgets(
+ new cloudwatch.GraphWidget({
+ title: 'Bytes written',
+ left: [
+ jobTotal(
+ sinkMetric('numBytesWrittenPerSecond', 'Sum'),
+ 'Accepted bytes/s (uncompressed)',
+ ),
+ ],
+ right: [
+ jobTotal(
+ sinkMetric('numBytesWritten', 'Sum'),
+ 'Accepted bytes since job start',
+ ),
+ jobTotal(
+ sinkMetric('numBytesOut', 'Sum'),
+ 'Attempted bytes since job start, including retries',
+ ),
+ ],
+ width: 12,
+ }),
+ new cloudwatch.GraphWidget({
+ title: 'Batch size',
+ left: [sinkMetric('batchSizeLines', 'Average', 'Lines per batch')],
+ right: [sinkMetric('batchSizeBytes', 'Average', 'Bytes per batch')],
+ width: 12,
+ }),
+ );
+ this.dashboard.addWidgets(
+ new cloudwatch.GraphWidget({
+ title: 'Batch outcomes',
+ left: [
+ jobTotal(sinkMetric('numBatchesSuccess', 'Sum'), 'Succeeded'),
+ jobTotal(sinkMetric('numBatchesRetried', 'Sum'), 'Retried'),
+ jobTotal(
+ sinkMetric('numBatchesCompletedWithDrops', 'Sum'),
+ 'Completed with drops',
+ ),
+ jobTotal(sinkMetric('numBatchesFailed', 'Sum'), 'Failed'),
+ ],
+ width: 12,
+ }),
+ new cloudwatch.GraphWidget({
+ title: 'Write errors by type',
+ left: [
+ jobTotal(sinkMetric('numServerErrors', 'Sum'), 'HTTP 5xx'),
+ jobTotal(sinkMetric('numClientErrors', 'Sum'), 'HTTP 4xx except 429'),
+ jobTotal(sinkMetric('numThrottledRequests', 'Sum'), 'HTTP 429'),
+ jobTotal(sinkMetric('numConnectionErrors', 'Sum'), 'Connection errors'),
+ jobTotal(sinkMetric('numWriteTimeouts', 'Sum'), 'Write timeouts'),
+ ],
+ width: 12,
+ }),
+ );
+ // Long-running health: a leak shows as heap after garbage collection,
+ // threads, or file descriptors creeping up, or old-generation GC growing.
+ this.dashboard.addWidgets(
+ new cloudwatch.GraphWidget({
+ title: 'JVM memory (%)',
+ left: [
+ applicationMetric('heapMemoryUtilization', 'Maximum', 'Heap (highest)'),
+ applicationMetric(
+ 'heapMemoryUtilization',
+ 'Minimum',
+ 'Heap after garbage collection (lowest)',
+ ),
+ applicationMetric('metaspaceMemoryUtilization', 'Maximum', 'Metaspace'),
+ ],
+ width: 8,
+ }),
+ new cloudwatch.GraphWidget({
+ title: 'Threads and file descriptors',
+ left: [
+ applicationMetric('threadsCount', 'Maximum', 'Threads'),
+ applicationMetric(
+ 'taskmanagerFileDescriptorsOpen',
+ 'Maximum',
+ 'Open file descriptors',
+ ),
+ ],
+ width: 8,
+ }),
+ new cloudwatch.GraphWidget({
+ title: 'Old-generation GC and checkpoints (ms)',
+ left: [
+ applicationMetric('oldGenerationGCTime', 'Maximum', 'Old-generation GC time'),
+ applicationMetric('lastCheckpointDuration', 'Maximum', 'Checkpoint duration'),
+ ],
+ width: 8,
+ }),
+ );
+ if (props.influxDbClusterName !== undefined) {
+ // SEARCH covers every node of the cluster without listing instance names.
+ const clusterMetric = (metricName: string, label: string) =>
+ new cloudwatch.MathExpression({
+ expression:
+ `SEARCH('{AWS/Timestream/InfluxDB,DbClusterName,DbInstanceName} ` +
+ `DbClusterName="${props.influxDbClusterName}" ` +
+ `MetricName="${metricName}"', 'Maximum', 60)`,
+ label,
+ period: PERIOD,
+ });
+ this.dashboard.addWidgets(
+ new cloudwatch.GraphWidget({
+ title: 'InfluxDB cluster',
+ left: [
+ clusterMetric('CPUUtilization', 'CPU %'),
+ clusterMetric('MemoryUtilization', 'Memory %'),
+ ],
+ width: 24,
+ }),
+ );
+ }
+ }
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/infra/package-lock.json b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/infra/package-lock.json
new file mode 100644
index 00000000..e939e73a
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/infra/package-lock.json
@@ -0,0 +1,527 @@
+{
+ "name": "flink-influxdb3-example-infrastructure",
+ "version": "0.1.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "flink-influxdb3-example-infrastructure",
+ "version": "0.1.0",
+ "dependencies": {
+ "aws-cdk-lib": "2.274.0",
+ "constructs": "10.8.1"
+ },
+ "devDependencies": {
+ "@types/node": "26.4.0",
+ "aws-cdk": "2.1146.1",
+ "ts-node": "10.9.2",
+ "typescript": "5.9.3"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/@aws-cdk/asset-awscli-v1": {
+ "version": "2.2.292",
+ "resolved": "https://registry.npmjs.org/@aws-cdk/asset-awscli-v1/-/asset-awscli-v1-2.2.292.tgz",
+ "integrity": "sha512-d4aMFsAFj19FtxVyw8IzlUKv5Zu4sIvgnEjI2IU6IWBJgVbJ4aFnadANqYa+6MwB1CQbGOg0jh8WE77M+Nb/9A==",
+ "license": "Apache-2.0"
+ },
+ "node_modules/@aws-cdk/asset-node-proxy-agent-v6": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/@aws-cdk/asset-node-proxy-agent-v6/-/asset-node-proxy-agent-v6-2.1.3.tgz",
+ "integrity": "sha512-98We1QWfin9vtuuQtNFhIIAEWb8CreyYTAP0Vn8HqSBoNiFJM9nZgifJeQawT9Wq0NX1HCNFlxCyTccIrK1PSA==",
+ "license": "Apache-2.0"
+ },
+ "node_modules/@aws-cdk/cloud-assembly-schema": {
+ "version": "55.2.0",
+ "resolved": "https://registry.npmjs.org/@aws-cdk/cloud-assembly-schema/-/cloud-assembly-schema-55.2.0.tgz",
+ "integrity": "sha512-DHfYrZdyJZwWlI5sOK97X7SDc5Ow+uH3w3/qnB/ZYtY530lEsLObOoq/Z8BcJM6bAwJI6ozIgg9VYg2ot+A1jQ==",
+ "bundleDependencies": [
+ "jsonschema",
+ "semver"
+ ],
+ "license": "Apache-2.0",
+ "dependencies": {
+ "jsonschema": "^1.5.0",
+ "semver": "^7.8.5"
+ },
+ "engines": {
+ "node": ">= 18.0.0"
+ }
+ },
+ "node_modules/@aws-cdk/cloud-assembly-schema/node_modules/jsonschema": {
+ "version": "1.5.0",
+ "inBundle": true,
+ "license": "MIT",
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/@aws-cdk/cloud-assembly-schema/node_modules/semver": {
+ "version": "7.8.5",
+ "inBundle": true,
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/@cspotcode/source-map-support": {
+ "version": "0.8.1",
+ "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz",
+ "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/trace-mapping": "0.3.9"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@jridgewell/resolve-uri": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
+ "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/@jridgewell/sourcemap-codec": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
+ "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@jridgewell/trace-mapping": {
+ "version": "0.3.9",
+ "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz",
+ "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/resolve-uri": "^3.0.3",
+ "@jridgewell/sourcemap-codec": "^1.4.10"
+ }
+ },
+ "node_modules/@tsconfig/node10": {
+ "version": "1.0.13",
+ "resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.13.tgz",
+ "integrity": "sha512-gcLdvR9HO1ZJBypsOGqaP6TFEzb6vIta0KSTLt9NAQ6pXQO3cRgSVyCN6pzYqI9DlJgY71XKO0dpDhCf08b3pg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@tsconfig/node12": {
+ "version": "1.0.11",
+ "resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz",
+ "integrity": "sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@tsconfig/node14": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz",
+ "integrity": "sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@tsconfig/node16": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.4.tgz",
+ "integrity": "sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/node": {
+ "version": "26.4.0",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-26.4.0.tgz",
+ "integrity": "sha512-faiGnoIrLH/V8cibOMEAZ8pMw6oXqSukl29ra4mN8GdaB2ZewzeaLj+INpV5N+Z1eKWzY+IzaIZH2EIR6YZRNQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": "~8.3.0"
+ }
+ },
+ "node_modules/acorn": {
+ "version": "8.18.0",
+ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz",
+ "integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "acorn": "bin/acorn"
+ },
+ "engines": {
+ "node": ">=0.4.0"
+ }
+ },
+ "node_modules/acorn-walk": {
+ "version": "8.3.5",
+ "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.5.tgz",
+ "integrity": "sha512-HEHNfbars9v4pgpW6SO1KSPkfoS0xVOM/9UzkJltjlsHZmJasxg8aXkuZa7SMf8vKGIBhpUsPluQSqhJFCqebw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "acorn": "^8.11.0"
+ },
+ "engines": {
+ "node": ">=0.4.0"
+ }
+ },
+ "node_modules/arg": {
+ "version": "4.1.3",
+ "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz",
+ "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/aws-cdk": {
+ "version": "2.1146.1",
+ "resolved": "https://registry.npmjs.org/aws-cdk/-/aws-cdk-2.1146.1.tgz",
+ "integrity": "sha512-Sb3RHuPt8yLP4BPFNl+D2li5wI9h4UL/+NYVq8FCxmDfUJwayzEOc/Tgb4wcixB8naOmPOLzhWkdbFx17tuhSg==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "cdk": "bin/cdk"
+ },
+ "engines": {
+ "node": ">= 18.0.0"
+ }
+ },
+ "node_modules/aws-cdk-lib": {
+ "version": "2.274.0",
+ "resolved": "https://registry.npmjs.org/aws-cdk-lib/-/aws-cdk-lib-2.274.0.tgz",
+ "integrity": "sha512-jez6nnPRPGLRv6PfaVUdJNnIQN/5OQQRyQRfdf2lbkww5Z2W4FJ+RIEW1TpYgJ3oLXoM23f9LGA1kxoqvF/sFg==",
+ "bundleDependencies": [
+ "@aws/cloudformation-validate",
+ "@balena/dockerignore",
+ "@aws-cdk/cloud-assembly-api",
+ "case",
+ "fs-extra",
+ "ignore",
+ "jsonschema",
+ "minimatch",
+ "punycode",
+ "semver",
+ "yaml",
+ "mime-types"
+ ],
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-cdk/asset-awscli-v1": "2.2.292",
+ "@aws-cdk/asset-node-proxy-agent-v6": "^2.1.3",
+ "@aws-cdk/cloud-assembly-api": "^2.5.0",
+ "@aws-cdk/cloud-assembly-schema": "^55.0.0",
+ "@aws/cloudformation-validate": "1.12.1",
+ "@balena/dockerignore": "^1.0.2",
+ "case": "1.6.3",
+ "fs-extra": "^11.4.1",
+ "ignore": "^5.3.2",
+ "jsonschema": "^1.5.0",
+ "mime-types": "^2.1.35",
+ "minimatch": "^10.2.6",
+ "punycode": "^2.3.1",
+ "semver": "^7.8.5",
+ "yaml": "1.10.3"
+ },
+ "engines": {
+ "node": ">= 20.0.0"
+ },
+ "peerDependencies": {
+ "constructs": "^10.5.0"
+ }
+ },
+ "node_modules/aws-cdk-lib/node_modules/@aws-cdk/cloud-assembly-api": {
+ "version": "2.5.0",
+ "inBundle": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "json-source-map": "^0.6.1",
+ "jsonschema": "^1.5.0",
+ "semver": "^7.8.5"
+ },
+ "engines": {
+ "node": ">= 18.0.0"
+ },
+ "peerDependencies": {
+ "@aws-cdk/cloud-assembly-schema": ">=55.0.0"
+ }
+ },
+ "node_modules/aws-cdk-lib/node_modules/@aws/cloudformation-validate": {
+ "version": "1.12.1",
+ "inBundle": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/aws-cdk-lib/node_modules/@balena/dockerignore": {
+ "version": "1.0.2",
+ "inBundle": true,
+ "license": "Apache-2.0"
+ },
+ "node_modules/aws-cdk-lib/node_modules/balanced-match": {
+ "version": "4.0.4",
+ "inBundle": true,
+ "license": "MIT",
+ "engines": {
+ "node": "18 || 20 || >=22"
+ }
+ },
+ "node_modules/aws-cdk-lib/node_modules/brace-expansion": {
+ "version": "5.0.12",
+ "inBundle": true,
+ "license": "MIT",
+ "dependencies": {
+ "balanced-match": "^4.0.2"
+ },
+ "engines": {
+ "node": "20 || >=22"
+ }
+ },
+ "node_modules/aws-cdk-lib/node_modules/case": {
+ "version": "1.6.3",
+ "inBundle": true,
+ "license": "(MIT OR GPL-3.0-or-later)",
+ "engines": {
+ "node": ">= 0.8.0"
+ }
+ },
+ "node_modules/aws-cdk-lib/node_modules/fs-extra": {
+ "version": "11.4.1",
+ "inBundle": true,
+ "license": "MIT",
+ "dependencies": {
+ "graceful-fs": "^4.2.0",
+ "jsonfile": "^6.0.1",
+ "universalify": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=14.14"
+ }
+ },
+ "node_modules/aws-cdk-lib/node_modules/graceful-fs": {
+ "version": "4.2.11",
+ "inBundle": true,
+ "license": "ISC"
+ },
+ "node_modules/aws-cdk-lib/node_modules/ignore": {
+ "version": "5.3.2",
+ "inBundle": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 4"
+ }
+ },
+ "node_modules/aws-cdk-lib/node_modules/json-source-map": {
+ "version": "0.6.1",
+ "inBundle": true,
+ "license": "MIT"
+ },
+ "node_modules/aws-cdk-lib/node_modules/jsonfile": {
+ "version": "6.2.1",
+ "inBundle": true,
+ "license": "MIT",
+ "dependencies": {
+ "universalify": "^2.0.0"
+ },
+ "optionalDependencies": {
+ "graceful-fs": "^4.1.6"
+ }
+ },
+ "node_modules/aws-cdk-lib/node_modules/jsonschema": {
+ "version": "1.5.0",
+ "inBundle": true,
+ "license": "MIT",
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/aws-cdk-lib/node_modules/mime-db": {
+ "version": "1.52.0",
+ "inBundle": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/aws-cdk-lib/node_modules/mime-types": {
+ "version": "2.1.35",
+ "inBundle": true,
+ "license": "MIT",
+ "dependencies": {
+ "mime-db": "1.52.0"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/aws-cdk-lib/node_modules/minimatch": {
+ "version": "10.2.6",
+ "inBundle": true,
+ "license": "BlueOak-1.0.0",
+ "dependencies": {
+ "brace-expansion": "^5.0.8"
+ },
+ "engines": {
+ "node": "18 || 20 || >=22"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
+ "node_modules/aws-cdk-lib/node_modules/punycode": {
+ "version": "2.3.1",
+ "inBundle": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/aws-cdk-lib/node_modules/semver": {
+ "version": "7.8.5",
+ "inBundle": true,
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/aws-cdk-lib/node_modules/universalify": {
+ "version": "2.0.1",
+ "inBundle": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 10.0.0"
+ }
+ },
+ "node_modules/aws-cdk-lib/node_modules/yaml": {
+ "version": "1.10.3",
+ "inBundle": true,
+ "license": "ISC",
+ "engines": {
+ "node": ">= 6"
+ }
+ },
+ "node_modules/constructs": {
+ "version": "10.8.1",
+ "resolved": "https://registry.npmjs.org/constructs/-/constructs-10.8.1.tgz",
+ "integrity": "sha512-98yGXYyhePqPYh3cYu8nzBERmAhC0DONe3UD03okK0nehZ7hYP4wgZuf02a04+uOWxnTJ5Rpp5m0GRNpwyLGGA==",
+ "license": "Apache-2.0"
+ },
+ "node_modules/create-require": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz",
+ "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/diff": {
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.4.tgz",
+ "integrity": "sha512-X07nttJQkwkfKfvTPG/KSnE2OMdcUCao6+eXF3wmnIQRn2aPAHH3VxDbDOdegkd6JbPsXqShpvEOHfAT+nCNwQ==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.3.1"
+ }
+ },
+ "node_modules/make-error": {
+ "version": "1.3.6",
+ "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz",
+ "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/ts-node": {
+ "version": "10.9.2",
+ "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz",
+ "integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@cspotcode/source-map-support": "^0.8.0",
+ "@tsconfig/node10": "^1.0.7",
+ "@tsconfig/node12": "^1.0.7",
+ "@tsconfig/node14": "^1.0.0",
+ "@tsconfig/node16": "^1.0.2",
+ "acorn": "^8.4.1",
+ "acorn-walk": "^8.1.1",
+ "arg": "^4.1.0",
+ "create-require": "^1.1.0",
+ "diff": "^4.0.1",
+ "make-error": "^1.1.1",
+ "v8-compile-cache-lib": "^3.0.1",
+ "yn": "3.1.1"
+ },
+ "bin": {
+ "ts-node": "dist/bin.js",
+ "ts-node-cwd": "dist/bin-cwd.js",
+ "ts-node-esm": "dist/bin-esm.js",
+ "ts-node-script": "dist/bin-script.js",
+ "ts-node-transpile-only": "dist/bin-transpile.js",
+ "ts-script": "dist/bin-script-deprecated.js"
+ },
+ "peerDependencies": {
+ "@swc/core": ">=1.2.50",
+ "@swc/wasm": ">=1.2.50",
+ "@types/node": "*",
+ "typescript": ">=2.7"
+ },
+ "peerDependenciesMeta": {
+ "@swc/core": {
+ "optional": true
+ },
+ "@swc/wasm": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/typescript": {
+ "version": "5.9.3",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "tsc": "bin/tsc",
+ "tsserver": "bin/tsserver"
+ },
+ "engines": {
+ "node": ">=14.17"
+ }
+ },
+ "node_modules/undici-types": {
+ "version": "8.3.0",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz",
+ "integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/v8-compile-cache-lib": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz",
+ "integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/yn": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz",
+ "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ }
+ }
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/infra/package.json b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/infra/package.json
new file mode 100644
index 00000000..7df4e92b
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/infra/package.json
@@ -0,0 +1,25 @@
+{
+ "name": "flink-influxdb3-example-infrastructure",
+ "version": "0.1.0",
+ "private": true,
+ "scripts": {
+ "build": "tsc",
+ "test": "npm run build && node --test dist/test/*.test.js && python3 -m unittest discover -s test -p '*_test.py'",
+ "synth": "npm run build && cdk synth --quiet",
+ "deploy": "npm run build && cdk deploy",
+ "destroy": "cdk destroy"
+ },
+ "dependencies": {
+ "aws-cdk-lib": "2.274.0",
+ "constructs": "10.8.1"
+ },
+ "devDependencies": {
+ "@types/node": "26.4.0",
+ "aws-cdk": "2.1146.1",
+ "ts-node": "10.9.2",
+ "typescript": "5.9.3"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/infra/test/fixtures/application-asset.txt b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/infra/test/fixtures/application-asset.txt
new file mode 100644
index 00000000..6994102b
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/infra/test/fixtures/application-asset.txt
@@ -0,0 +1 @@
+CDK test fixture; this is not a deployable JAR.
diff --git a/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/infra/test/flink_application_lifecycle_test.py b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/infra/test/flink_application_lifecycle_test.py
new file mode 100644
index 00000000..9d9e88be
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/infra/test/flink_application_lifecycle_test.py
@@ -0,0 +1,426 @@
+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+import importlib.util
+import pathlib
+import sys
+import types
+import unittest
+
+
+class _ResourceNotFoundException(Exception):
+ pass
+
+
+class _ResourceInUseException(Exception):
+ pass
+
+
+class _FakeKinesisAnalyticsClient:
+ exceptions = types.SimpleNamespace(
+ ResourceNotFoundException=_ResourceNotFoundException,
+ ResourceInUseException=_ResourceInUseException,
+ )
+
+ def __init__(
+ self,
+ status,
+ operation_status="IN_PROGRESS",
+ operation_error=None,
+ start_resource_in_use_count=0,
+ application_operations=None,
+ ):
+ self.status = status
+ self.operation_status = operation_status
+ self.operation_error = operation_error
+ self.start_resource_in_use_count = start_resource_in_use_count
+ self.application_operations = application_operations or []
+ self.start_calls = []
+ self.stop_calls = []
+ self.list_operation_calls = []
+ self.describe_operation_calls = []
+
+ def describe_application(self, **_kwargs):
+ if self.status is None:
+ raise _ResourceNotFoundException()
+ return {
+ "ApplicationDetail": {
+ "ApplicationStatus": self.status,
+ }
+ }
+
+ def start_application(self, **kwargs):
+ self.start_calls.append(kwargs)
+ if self.start_resource_in_use_count > 0:
+ self.start_resource_in_use_count -= 1
+ raise _ResourceInUseException()
+ return {"OperationId": "start-operation-id"}
+
+ def stop_application(self, **kwargs):
+ self.stop_calls.append(kwargs)
+ return {"OperationId": "stop-operation-id"}
+
+ def list_application_operations(self, **kwargs):
+ self.list_operation_calls.append(kwargs)
+ return {
+ "ApplicationOperationInfoList": self.application_operations,
+ }
+
+ def describe_application_operation(self, **kwargs):
+ self.describe_operation_calls.append(kwargs)
+ details = {
+ "Operation": kwargs.get("OperationId"),
+ "OperationStatus": self.operation_status,
+ }
+ if self.operation_error is not None:
+ details["OperationFailureDetails"] = {
+ "ErrorInfo": {
+ "ErrorString": self.operation_error,
+ }
+ }
+ return {"ApplicationOperationInfoDetails": details}
+
+
+def _load_handler(
+ status,
+ operation_status="IN_PROGRESS",
+ operation_error=None,
+ start_resource_in_use_count=0,
+ application_operations=None,
+):
+ fake_client = _FakeKinesisAnalyticsClient(
+ status,
+ operation_status,
+ operation_error,
+ start_resource_in_use_count,
+ application_operations,
+ )
+ fake_boto3 = types.SimpleNamespace(client=lambda _service_name: fake_client)
+ sys.modules["boto3"] = fake_boto3
+
+ handler_path = (
+ pathlib.Path(__file__).parents[1]
+ / "lambda"
+ / "flink-application-lifecycle"
+ / "handler.py"
+ )
+ spec = importlib.util.spec_from_file_location(
+ "flink_application_lifecycle_handler",
+ handler_path,
+ )
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module, fake_client
+
+
+def _event(
+ request_type="Create",
+ physical_resource_id=None,
+ operation_id=None,
+ operation_name=None,
+):
+ event = {
+ "RequestType": request_type,
+ "ResourceProperties": {
+ "ApplicationName": "influxdb3-flink-example",
+ },
+ }
+ if physical_resource_id is not None:
+ event["PhysicalResourceId"] = physical_resource_id
+ if operation_id is not None:
+ event["LifecycleOperationId"] = operation_id
+ if operation_name is not None:
+ event["LifecycleOperation"] = operation_name
+ return event
+
+
+class FlinkApplicationLifecycleTest(unittest.TestCase):
+ def test_create_requests_start_from_ready(self):
+ handler, client = _load_handler("READY")
+
+ result = handler.on_event(_event(), None)
+
+ self.assertEqual(
+ result["PhysicalResourceId"],
+ "influxdb3-flink-example",
+ )
+ self.assertEqual(
+ result["LifecycleOperationId"],
+ "start-operation-id",
+ )
+ self.assertEqual(result["LifecycleOperation"], "StartApplication")
+ self.assertEqual(len(client.start_calls), 1)
+ self.assertEqual(
+ client.start_calls[0]["RunConfiguration"][
+ "ApplicationRestoreConfiguration"
+ ]["ApplicationRestoreType"],
+ "SKIP_RESTORE_FROM_SNAPSHOT",
+ )
+
+ def test_create_tracks_an_existing_start(self):
+ handler, client = _load_handler(
+ "STARTING",
+ application_operations=[
+ {
+ "Operation": "StartApplication",
+ "OperationId": "existing-start-operation-id",
+ "OperationStatus": "IN_PROGRESS",
+ }
+ ],
+ )
+
+ result = handler.on_event(_event(), None)
+
+ self.assertEqual(
+ result["LifecycleOperationId"],
+ "existing-start-operation-id",
+ )
+ self.assertEqual(client.start_calls, [])
+
+ def test_create_rejects_an_unrelated_transitional_state(self):
+ handler, client = _load_handler("UPDATING")
+
+ with self.assertRaisesRegex(
+ RuntimeError,
+ "from status 'UPDATING'",
+ ):
+ handler.on_event(_event(), None)
+
+ self.assertEqual(client.start_calls, [])
+
+ def test_resource_in_use_recovers_and_tracks_in_progress_start(self):
+ handler, client = _load_handler(
+ "READY",
+ start_resource_in_use_count=1,
+ application_operations=[
+ {
+ "Operation": "StartApplication",
+ "OperationId": "existing-start-operation-id",
+ "OperationStatus": "IN_PROGRESS",
+ }
+ ],
+ )
+
+ initial_result = handler.on_event(_event(), None)
+
+ self.assertEqual(
+ initial_result["LifecycleOperationId"],
+ "existing-start-operation-id",
+ )
+ self.assertEqual(initial_result["LifecycleOperation"], "StartApplication")
+ self.assertEqual(
+ client.list_operation_calls,
+ [
+ {
+ "ApplicationName": "influxdb3-flink-example",
+ "Limit": 1,
+ "Operation": "StartApplication",
+ "OperationStatus": "IN_PROGRESS",
+ }
+ ],
+ )
+
+ client.operation_status = "FAILED"
+ client.operation_error = "endpoint must contain a host"
+ completion_event = _event()
+ completion_event.update(initial_result)
+
+ with self.assertRaisesRegex(
+ RuntimeError,
+ "endpoint must contain a host",
+ ):
+ handler.is_complete(completion_event, None)
+
+ def test_resource_in_use_without_observable_start_fails(self):
+ handler, _client = _load_handler(
+ "READY",
+ start_resource_in_use_count=1,
+ )
+
+ with self.assertRaisesRegex(
+ RuntimeError,
+ "no in-progress start operation could be found",
+ ):
+ handler.on_event(_event(), None)
+
+ def test_delete_preserves_the_cloudformation_physical_resource_id(self):
+ handler, client = _load_handler("RUNNING")
+ event = _event(
+ "Delete",
+ physical_resource_id="cloudformation-generated-id",
+ )
+
+ result = handler.on_event(event, None)
+
+ self.assertEqual(
+ result["PhysicalResourceId"],
+ "cloudformation-generated-id",
+ )
+ self.assertEqual(
+ result["LifecycleOperationId"],
+ "stop-operation-id",
+ )
+ self.assertEqual(result["LifecycleOperation"], "StopApplication")
+ self.assertEqual(
+ client.stop_calls,
+ [{"ApplicationName": "influxdb3-flink-example"}],
+ )
+
+ def test_delete_preserves_the_physical_id_when_application_is_missing(self):
+ handler, client = _load_handler(None)
+ event = _event(
+ "Delete",
+ physical_resource_id="cloudformation-generated-id",
+ )
+
+ result = handler.on_event(event, None)
+
+ self.assertEqual(
+ result["PhysicalResourceId"],
+ "cloudformation-generated-id",
+ )
+ self.assertNotIn("LifecycleOperationId", result)
+ self.assertEqual(client.stop_calls, [])
+
+ def test_running_application_completes_start(self):
+ handler, _client = _load_handler("RUNNING")
+
+ self.assertEqual(
+ handler.is_complete(_event(), None),
+ {"IsComplete": True},
+ )
+
+ def test_failed_start_operation_fails_without_waiting_for_timeout(self):
+ handler, client = _load_handler(
+ "READY",
+ operation_status="FAILED",
+ operation_error="endpoint must contain a host",
+ )
+ event = _event(
+ operation_id="start-operation-id",
+ operation_name="StartApplication",
+ )
+
+ with self.assertRaisesRegex(
+ RuntimeError,
+ "endpoint must contain a host",
+ ):
+ handler.is_complete(event, None)
+
+ self.assertEqual(
+ client.describe_operation_calls,
+ [
+ {
+ "ApplicationName": "influxdb3-flink-example",
+ "OperationId": "start-operation-id",
+ }
+ ],
+ )
+ self.assertEqual(client.start_calls, [])
+
+ def test_failed_operation_error_is_bounded_and_keeps_the_root_cause(self):
+ operation_error = "outer failure " + ("x" * 4000) + " root cause"
+ handler, _client = _load_handler(
+ "READY",
+ operation_status="FAILED",
+ operation_error=operation_error,
+ )
+ event = _event(
+ operation_id="start-operation-id",
+ operation_name="StartApplication",
+ )
+
+ with self.assertRaises(RuntimeError) as raised:
+ handler.is_complete(event, None)
+
+ message = str(raised.exception)
+ self.assertLess(len(message), 1500)
+ self.assertIn("outer failure", message)
+ self.assertIn("root cause", message)
+
+ def test_in_progress_start_operation_keeps_waiting(self):
+ handler, _client = _load_handler("READY")
+ event = _event(
+ operation_id="start-operation-id",
+ operation_name="StartApplication",
+ )
+
+ self.assertEqual(
+ handler.is_complete(event, None),
+ {"IsComplete": False},
+ )
+
+ def test_successful_start_that_returns_to_ready_fails(self):
+ handler, _client = _load_handler(
+ "READY",
+ operation_status="SUCCESSFUL",
+ )
+ event = _event(
+ operation_id="start-operation-id",
+ operation_name="StartApplication",
+ )
+
+ with self.assertRaisesRegex(
+ RuntimeError,
+ "returned to READY",
+ ):
+ handler.is_complete(event, None)
+
+ def test_delete_stops_running_application(self):
+ handler, client = _load_handler("RUNNING")
+
+ result = handler.is_complete(_event("Delete"), None)
+
+ self.assertEqual(result, {"IsComplete": False})
+ self.assertEqual(
+ client.stop_calls,
+ [{"ApplicationName": "influxdb3-flink-example"}],
+ )
+
+ def test_delete_is_complete_when_application_is_ready(self):
+ handler, client = _load_handler("READY")
+
+ self.assertEqual(
+ handler.is_complete(_event("Delete"), None),
+ {"IsComplete": True},
+ )
+ self.assertEqual(client.stop_calls, [])
+
+ def test_failed_or_cancelled_stop_operation_does_not_block_delete(self):
+ for operation_status, operation_error in (
+ ("FAILED", "stop failed"),
+ ("CANCELLED", "stop cancelled"),
+ ):
+ with self.subTest(operation_status=operation_status):
+ handler, client = _load_handler(
+ "RUNNING",
+ operation_status=operation_status,
+ operation_error=operation_error,
+ )
+ event = _event(
+ "Delete",
+ physical_resource_id="cloudformation-generated-id",
+ operation_id="stop-operation-id",
+ operation_name="StopApplication",
+ )
+
+ with self.assertLogs(handler._LOGGER, level="WARNING") as logs:
+ result = handler.is_complete(event, None)
+
+ self.assertEqual(result, {"IsComplete": True})
+ self.assertIn(operation_status.lower(), logs.output[0])
+ self.assertIn(operation_error, logs.output[0])
+ self.assertEqual(client.stop_calls, [])
+
+ def test_delete_is_complete_from_terminal_non_running_state(self):
+ handler, client = _load_handler("ROLLED_BACK")
+
+ self.assertEqual(
+ handler.is_complete(_event("Delete"), None),
+ {"IsComplete": True},
+ )
+ self.assertEqual(client.stop_calls, [])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/infra/test/managed-flink-example-stack.test.ts b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/infra/test/managed-flink-example-stack.test.ts
new file mode 100644
index 00000000..52ad9ec7
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/infra/test/managed-flink-example-stack.test.ts
@@ -0,0 +1,520 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ */
+
+import * as assert from 'node:assert/strict';
+import * as path from 'node:path';
+import { test } from 'node:test';
+import * as cdk from 'aws-cdk-lib';
+import { Match, Template } from 'aws-cdk-lib/assertions';
+import {
+ ManagedFlinkExampleStack,
+ ManagedFlinkExampleStackProps,
+} from '../lib/managed-flink-example-stack';
+
+function synthesizeTemplate(
+ overrides: Partial = {},
+): Template {
+ const app = new cdk.App();
+ const stack = new ManagedFlinkExampleStack(app, 'TestStack', {
+ env: {
+ account: '111111111111',
+ region: 'us-east-1',
+ },
+ applicationJarPath: path.resolve(
+ __dirname,
+ '../../test/fixtures/application-asset.txt',
+ ),
+ lifecycleCodePath: path.resolve(
+ __dirname,
+ '../../lambda/flink-application-lifecycle',
+ ),
+ ...overrides,
+ });
+ return Template.fromStack(stack);
+}
+
+test('accepts an existing InfluxDB endpoint and secret as parameters', () => {
+ const template = synthesizeTemplate();
+
+ template.hasParameter('InfluxDbEndpoint', {
+ Type: 'String',
+ AllowedPattern:
+ '^https://(?:\\[[0-9A-Fa-f:]+\\]|[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)*)' +
+ '(?::[0-9]{1,5})?/?$',
+ });
+ template.hasParameter('InfluxDbSecretArn', {
+ Type: 'String',
+ AllowedPattern: 'arn:[^:]+:secretsmanager:[^:]+:[0-9]{12}:secret:.+',
+ });
+ template.resourceCountIs('AWS::Timestream::InfluxDBCluster', 0);
+ template.resourceCountIs('AWS::EC2::VPC', 0);
+ template.resourceCountIs('Custom::InfluxDBParameterGroup', 0);
+ template.resourceCountIs('Custom::InfluxDB3Database', 0);
+});
+
+test('rejects an InfluxDB endpoint without a valid URI host', () => {
+ assert.throws(
+ () =>
+ synthesizeTemplate({
+ influxDbEndpoint: 'https://YOUR_ENDPOINT:8181',
+ }),
+ /influxDbEndpoint must be an HTTPS base URL with a valid host/,
+ );
+});
+
+test('rejects a plaintext HTTP InfluxDB endpoint', () => {
+ assert.throws(
+ () =>
+ synthesizeTemplate({
+ influxDbEndpoint:
+ 'http://0123456789-abcdefghijkl.us-east-1.timestream-influxdb.amazonaws.com:8181',
+ }),
+ /influxDbEndpoint must be an HTTPS base URL/,
+ );
+});
+
+test('accepts a concrete InfluxDB endpoint with a valid host', () => {
+ const endpoint =
+ 'https://0123456789-abcdefghijkl.us-east-1.timestream-influxdb.amazonaws.com:8181';
+ const template = synthesizeTemplate({
+ influxDbEndpoint: endpoint,
+ });
+
+ template.hasResourceProperties('AWS::KinesisAnalyticsV2::Application', {
+ ApplicationConfiguration: Match.objectLike({
+ EnvironmentProperties: {
+ PropertyGroups: Match.arrayWith([
+ Match.objectLike({
+ PropertyGroupId: 'InfluxDB3',
+ PropertyMap: Match.objectLike({
+ endpoint,
+ }),
+ }),
+ ]),
+ },
+ }),
+ });
+});
+
+test('accepts an InfluxDB database name containing underscores', () => {
+ const databaseName = 'my_sensors';
+ const template = synthesizeTemplate({ databaseName });
+
+ template.hasResourceProperties('AWS::KinesisAnalyticsV2::Application', {
+ ApplicationConfiguration: Match.objectLike({
+ EnvironmentProperties: {
+ PropertyGroups: Match.arrayWith([
+ Match.objectLike({
+ PropertyGroupId: 'InfluxDB3',
+ PropertyMap: Match.objectLike({
+ database: databaseName,
+ }),
+ }),
+ ]),
+ },
+ }),
+ });
+});
+
+test('deploys the Maven bundle as a Managed Flink application', () => {
+ const template = synthesizeTemplate();
+
+ template.resourceCountIs('AWS::KinesisAnalyticsV2::Application', 1);
+ template.hasResourceProperties('AWS::KinesisAnalyticsV2::Application', {
+ ApplicationMode: 'STREAMING',
+ RuntimeEnvironment: 'FLINK-2_3',
+ ApplicationConfiguration: Match.objectLike({
+ ApplicationCodeConfiguration: Match.objectLike({
+ CodeContentType: 'ZIPFILE',
+ CodeContent: Match.objectLike({
+ S3ContentLocation: Match.objectLike({
+ BucketARN: Match.anyValue(),
+ FileKey: Match.anyValue(),
+ }),
+ }),
+ }),
+ EnvironmentProperties: {
+ PropertyGroups: Match.arrayWith([
+ Match.objectLike({
+ PropertyGroupId: 'KinesisSource',
+ PropertyMap: Match.objectLike({
+ initialPosition: 'LATEST',
+ }),
+ }),
+ Match.objectLike({
+ PropertyGroupId: 'InfluxDB3',
+ PropertyMap: {
+ endpoint: { Ref: 'InfluxDbEndpoint' },
+ database: 'sensors',
+ secretId: { Ref: 'InfluxDbSecretArn' },
+ secretJsonField: 'token',
+ region: {
+ 'Fn::Select': [
+ 3,
+ {
+ 'Fn::Split': [':', { Ref: 'InfluxDbSecretArn' }],
+ },
+ ],
+ },
+ },
+ }),
+ ]),
+ },
+ FlinkApplicationConfiguration: Match.objectLike({
+ ParallelismConfiguration: Match.objectLike({
+ AutoScalingEnabled: false,
+ Parallelism: 1,
+ }),
+ }),
+ }),
+ });
+
+ const resources = template.findResources(
+ 'AWS::KinesisAnalyticsV2::Application',
+ );
+ const application = Object.values(resources)[0];
+ assert.equal(
+ application.Properties.ApplicationConfiguration.VpcConfigurations,
+ undefined,
+ );
+});
+
+test('grants access to only the configured token secret', () => {
+ const template = synthesizeTemplate();
+ const serializedTemplate = JSON.stringify(template.toJSON());
+
+ assert.match(serializedTemplate, /secretsmanager:GetSecretValue/);
+ assert.match(serializedTemplate, /InfluxDbSecretArn/);
+ assert.match(serializedTemplate, /-\?\?\?\?\?\?/);
+ assert.doesNotMatch(serializedTemplate, /timestream-influxdb:/);
+});
+
+test('uses supplied networking for a private InfluxDB endpoint', () => {
+ const template = synthesizeTemplate({
+ flinkSubnetIds: ['subnet-11111111', 'subnet-22222222'],
+ flinkSecurityGroupIds: ['sg-11111111'],
+ });
+
+ template.hasResourceProperties('AWS::KinesisAnalyticsV2::Application', {
+ ApplicationConfiguration: Match.objectLike({
+ VpcConfigurations: [
+ {
+ SecurityGroupIds: ['sg-11111111'],
+ SubnetIds: ['subnet-11111111', 'subnet-22222222'],
+ },
+ ],
+ }),
+ });
+ assert.match(
+ JSON.stringify(template.toJSON()),
+ /ec2:CreateNetworkInterface/,
+ );
+ assert.match(
+ JSON.stringify(template.toJSON()),
+ /ec2:CreateNetworkInterfacePermission/,
+ );
+ assert.match(JSON.stringify(template.toJSON()), /ec2:DescribeDhcpOptions/);
+});
+
+test('grants KMS decrypt when a customer-managed secret key is supplied', () => {
+ const template = synthesizeTemplate({
+ influxDbSecretKmsKeyArn:
+ 'arn:aws:kms:us-east-1:111111111111:key/11111111-2222-3333-4444-555555555555',
+ });
+
+ const serializedTemplate = JSON.stringify(template.toJSON());
+ assert.match(serializedTemplate, /kms:Decrypt/);
+ assert.match(serializedTemplate, /11111111-2222-3333-4444-555555555555/);
+});
+
+test('starts and stops the Managed Flink application with a custom resource', () => {
+ const template = synthesizeTemplate();
+
+ template.resourceCountIs('Custom::FlinkApplicationLifecycle', 1);
+ template.hasResourceProperties('Custom::FlinkApplicationLifecycle', {
+ ServiceTimeout: '3300',
+ ApplicationName: Match.anyValue(),
+ DeploymentFingerprint: Match.anyValue(),
+ });
+
+ const serializedTemplate = JSON.stringify(template.toJSON());
+ assert.match(serializedTemplate, /kinesisanalytics:StartApplication/);
+ assert.match(serializedTemplate, /kinesisanalytics:StopApplication/);
+ assert.match(serializedTemplate, /kinesisanalytics:DescribeApplication/);
+ assert.match(serializedTemplate, /kinesisanalytics:ListApplicationOperations/);
+ assert.match(
+ serializedTemplate,
+ /kinesisanalytics:DescribeApplicationOperation/,
+ );
+ assert.doesNotMatch(serializedTemplate, /apiv3_/);
+});
+
+function propertyGroups(template: Template): Record> {
+ const resources = template.findResources(
+ 'AWS::KinesisAnalyticsV2::Application',
+ );
+ const application = Object.values(resources)[0];
+ const groups =
+ application.Properties.ApplicationConfiguration.EnvironmentProperties
+ .PropertyGroups as { PropertyGroupId: string; PropertyMap: Record }[];
+ return Object.fromEntries(
+ groups.map((group) => [group.PropertyGroupId, group.PropertyMap]),
+ );
+}
+
+test('selects the DataStream pipeline by default', () => {
+ const groups = propertyGroups(synthesizeTemplate());
+
+ assert.deepEqual(groups.Application, { pipeline: 'datastream' });
+});
+
+test('selects the SQL pipeline', () => {
+ const groups = propertyGroups(synthesizeTemplate({ pipeline: 'sql' }));
+
+ assert.deepEqual(groups.Application, { pipeline: 'sql' });
+});
+
+test('accepts the pipeline in any case', () => {
+ const groups = propertyGroups(synthesizeTemplate({ pipeline: 'SQL' }));
+
+ assert.deepEqual(groups.Application, { pipeline: 'sql' });
+});
+
+test('rejects an unknown pipeline', () => {
+ assert.throws(
+ () => synthesizeTemplate({ pipeline: 'table' }),
+ /pipeline must be one of datastream, sql, datagen/,
+ );
+});
+
+test('runs the datagen pipeline without a Kinesis stream', () => {
+ const template = synthesizeTemplate({
+ pipeline: 'datagen',
+ dataGenProperties: { ratePerSecond: '1000', runId: 'smoke' },
+ });
+ const groups = propertyGroups(template);
+
+ template.resourceCountIs('AWS::Kinesis::Stream', 0);
+ assert.deepEqual(groups.Application, { pipeline: 'datagen' });
+ assert.equal(groups.KinesisSource, undefined);
+ assert.deepEqual(groups.DataGen, { ratePerSecond: '1000', runId: 'smoke' });
+ assert.ok(groups.InfluxDB3 !== undefined);
+ assert.equal(template.findOutputs('KinesisStreamName').KinesisStreamName, undefined);
+ assert.doesNotMatch(JSON.stringify(template.toJSON()), /kinesis:GetRecords/);
+});
+
+test('omits empty optional property groups', () => {
+ const groups = propertyGroups(
+ synthesizeTemplate({ pipeline: 'datagen', dataGenProperties: {}, sinkProperties: {} }),
+ );
+
+ assert.equal(groups.DataGen, undefined);
+ assert.equal(groups.Sink, undefined);
+});
+
+test('passes Sink properties to the application', () => {
+ const groups = propertyGroups(
+ synthesizeTemplate({ sinkProperties: { 'sink.batch.max-size': '50000' } }),
+ );
+
+ assert.deepEqual(groups.Sink, { 'sink.batch.max-size': '50000' });
+});
+
+test('rejects DataGen properties for other pipelines', () => {
+ assert.throws(
+ () => synthesizeTemplate({ dataGenProperties: { ratePerSecond: '1' } }),
+ /dataGenProperties requires the datagen pipeline/,
+ );
+});
+
+test('configures parallelism and checkpointing', () => {
+ const template = synthesizeTemplate({
+ parallelism: 8,
+ parallelismPerKpu: 2,
+ checkpointingEnabled: true,
+ checkpointIntervalMillis: 30_000,
+ });
+
+ template.hasResourceProperties('AWS::KinesisAnalyticsV2::Application', {
+ ApplicationConfiguration: Match.objectLike({
+ FlinkApplicationConfiguration: Match.objectLike({
+ ParallelismConfiguration: {
+ ConfigurationType: 'CUSTOM',
+ AutoScalingEnabled: false,
+ Parallelism: 8,
+ ParallelismPerKPU: 2,
+ },
+ CheckpointConfiguration: {
+ ConfigurationType: 'CUSTOM',
+ CheckpointingEnabled: true,
+ CheckpointInterval: 30_000,
+ },
+ }),
+ }),
+ });
+});
+
+test('enables checkpointing by default', () => {
+ synthesizeTemplate().hasResourceProperties('AWS::KinesisAnalyticsV2::Application', {
+ ApplicationConfiguration: Match.objectLike({
+ FlinkApplicationConfiguration: Match.objectLike({
+ CheckpointConfiguration: {
+ ConfigurationType: 'CUSTOM',
+ CheckpointingEnabled: true,
+ CheckpointInterval: 60_000,
+ },
+ }),
+ }),
+ });
+});
+
+test('rejects invalid parallelism settings', () => {
+ assert.throws(
+ () => synthesizeTemplate({ parallelism: 0 }),
+ /parallelism must be an integer of at least 1/,
+ );
+ assert.throws(
+ () => synthesizeTemplate({ parallelism: 2.5 }),
+ /parallelism must be an integer of at least 1/,
+ );
+ assert.throws(
+ () => synthesizeTemplate({ parallelismPerKpu: 9 }),
+ /parallelismPerKpu must be an integer from 1 to 8/,
+ );
+ assert.throws(
+ () => synthesizeTemplate({ checkpointIntervalMillis: 0 }),
+ /checkpointIntervalMillis must be an integer of at least 1/,
+ );
+});
+
+function deploymentFingerprint(template: Template): string {
+ const resources = template.findResources('Custom::FlinkApplicationLifecycle');
+ return JSON.stringify(
+ Object.values(resources)[0].Properties.DeploymentFingerprint,
+ );
+}
+
+test('changes the deployment fingerprint when the pipeline changes', () => {
+ const datastream = deploymentFingerprint(synthesizeTemplate());
+ const sql = deploymentFingerprint(synthesizeTemplate({ pipeline: 'sql' }));
+
+ assert.notEqual(datastream, sql);
+});
+
+test('changes the deployment fingerprint when tuning settings change', () => {
+ const baseline = deploymentFingerprint(synthesizeTemplate({ pipeline: 'datagen' }));
+
+ for (const props of [
+ { parallelism: 2 },
+ { parallelismPerKpu: 2 },
+ { checkpointingEnabled: false },
+ { checkpointIntervalMillis: 30_000 },
+ { dataGenProperties: { ratePerSecond: '1000' } },
+ { sinkProperties: { 'sink.batch.max-size': '50000' } },
+ ]) {
+ assert.notEqual(
+ deploymentFingerprint(synthesizeTemplate({ pipeline: 'datagen', ...props })),
+ baseline,
+ JSON.stringify(props),
+ );
+ }
+});
+
+test('alarms on dropped records from the published sink metrics', () => {
+ const template = synthesizeTemplate();
+
+ template.hasResourceProperties('AWS::KinesisAnalyticsV2::Application', {
+ ApplicationConfiguration: Match.objectLike({
+ FlinkApplicationConfiguration: Match.objectLike({
+ MonitoringConfiguration: Match.objectLike({
+ MetricsLevel: 'APPLICATION',
+ }),
+ }),
+ }),
+ });
+ template.resourceCountIs('AWS::CloudWatch::Alarm', 1);
+ template.hasResourceProperties('AWS::CloudWatch::Alarm', {
+ Namespace: 'AWS/KinesisAnalytics',
+ MetricName: 'numRecordsDroppedPerSecond',
+ Dimensions: Match.arrayWith([
+ { Name: 'Application', Value: { Ref: 'FlinkApplication' } },
+ { Name: 'Connector', Value: 'TimestreamInfluxDB3' },
+ ]),
+ Statistic: 'Sum',
+ Period: 60,
+ Threshold: 0,
+ ComparisonOperator: 'GreaterThanThreshold',
+ EvaluationPeriods: 1,
+ TreatMissingData: 'notBreaching',
+ });
+});
+
+test('creates the sink dashboard panels', () => {
+ const template = synthesizeTemplate();
+
+ template.resourceCountIs('AWS::CloudWatch::Dashboard', 1);
+ const dashboards = template.findResources('AWS::CloudWatch::Dashboard');
+ const body = JSON.stringify(
+ Object.values(dashboards)[0].Properties.DashboardBody,
+ );
+ for (const title of [
+ 'Throughput',
+ 'Write latency (ms)',
+ 'Dropped records and failures',
+ 'Throttling and retries',
+ 'Buffered bytes and in-flight requests',
+ 'Job health',
+ 'Bytes written',
+ 'Batch size',
+ 'Batch outcomes',
+ 'Write errors by type',
+ 'JVM memory (%)',
+ 'Threads and file descriptors',
+ 'Old-generation GC and checkpoints (ms)',
+ ]) {
+ assert.ok(body.includes(`\\"title\\":\\"${title}\\"`), title);
+ }
+ for (const metric of [
+ 'numRecordsWrittenPerSecond',
+ 'writeLatencyP99Millis',
+ 'numRecordsDroppedPerSecond',
+ 'numThrottledRequests',
+ 'numBufferedBytes',
+ 'heapMemoryUtilization',
+ 'busyTimeMsPerSecond',
+ 'numRestarts',
+ 'numBytesWrittenPerSecond',
+ 'numBytesOut',
+ 'numBatchesRetried',
+ 'numServerErrors',
+ 'numConnectionErrors',
+ 'numRetryDelayMillis',
+ 'maxRetryAfterMillis',
+ 'metaspaceMemoryUtilization',
+ 'threadsCount',
+ 'taskmanagerFileDescriptorsOpen',
+ 'oldGenerationGCTime',
+ 'lastCheckpointDuration',
+ ]) {
+ assert.ok(body.includes(metric), metric);
+ }
+ // Summed subtask reports are divided by the job-level report count.
+ assert.ok(body.includes('numRecordsWrittenPerSecond / reports'));
+ assert.ok(body.includes('uptime'));
+ assert.ok(!body.includes('InfluxDB cluster'));
+});
+
+test('adds an InfluxDB cluster panel when the cluster name is supplied', () => {
+ const template = synthesizeTemplate({ influxDbClusterName: 'sensors-cluster' });
+ const dashboards = template.findResources('AWS::CloudWatch::Dashboard');
+ const body = JSON.stringify(
+ Object.values(dashboards)[0].Properties.DashboardBody,
+ );
+
+ assert.ok(body.includes('InfluxDB cluster'));
+ assert.ok(body.includes('sensors-cluster'));
+ assert.ok(body.includes('CPUUtilization'));
+ assert.ok(body.includes('MemoryUtilization'));
+});
diff --git a/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/infra/tsconfig.json b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/infra/tsconfig.json
new file mode 100644
index 00000000..7b1d01ee
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/example/managed-flink/infra/tsconfig.json
@@ -0,0 +1,39 @@
+{
+ "compilerOptions": {
+ "alwaysStrict": true,
+ "declaration": true,
+ "esModuleInterop": true,
+ "experimentalDecorators": true,
+ "inlineSourceMap": true,
+ "inlineSources": true,
+ "lib": [
+ "es2022"
+ ],
+ "module": "commonjs",
+ "noFallthroughCasesInSwitch": true,
+ "noImplicitAny": true,
+ "noImplicitReturns": true,
+ "noImplicitThis": true,
+ "outDir": "dist",
+ "resolveJsonModule": true,
+ "strict": true,
+ "strictNullChecks": true,
+ "target": "ES2022",
+ "typeRoots": [
+ "./node_modules/@types"
+ ],
+ "types": [
+ "node"
+ ]
+ },
+ "include": [
+ "bin/**/*.ts",
+ "lib/**/*.ts",
+ "test/**/*.ts"
+ ],
+ "exclude": [
+ "cdk.out",
+ "dist",
+ "node_modules"
+ ]
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/pom.xml b/integrations/flink_connector/flink-connector-influxdb/pom.xml
new file mode 100644
index 00000000..2025e1c2
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/pom.xml
@@ -0,0 +1,614 @@
+
+
+
+ 4.0.0
+
+ software.amazon.timestream
+ flink-connector-timestream-influxdb3
+ 0.1.0
+ Flink Connector for Amazon Timestream for InfluxDB 3
+ An Apache Flink DataStream and Table API sink for Amazon Timestream for InfluxDB 3.
+ jar
+ https://github.com/awslabs/amazon-timestream-tools/tree/mainline/integrations/flink_connector/flink-connector-influxdb
+
+
+
+ Apache License, Version 2.0
+ https://www.apache.org/licenses/LICENSE-2.0.txt
+ repo
+
+
+
+
+
+ amazonwebservices
+ Amazon Web Services
+ https://aws.amazon.com
+
+
+
+
+ https://github.com/awslabs/amazon-timestream-tools/tree/mainline/integrations/flink_connector/flink-connector-influxdb
+ scm:git:https://github.com/awslabs/amazon-timestream-tools.git
+ scm:git:ssh://git@github.com/awslabs/amazon-timestream-tools.git
+
+
+
+ UTF-8
+ 17
+
+ 2.3.0
+ 1.10.0
+ 2.31.78
+ 2.21.8
+ 1.81.0
+ 4.2.19.Final
+ 1.7.36
+
+ 5.12.1
+ 3.27.3
+ 3.12.1
+ 1.21.4
+ 3.14.0
+ 3.5.3
+ 3.5.3
+ 3.1.0
+ ${project.build.directory}/test-tls
+ changeit
+ 3.3.1
+ 3.11.2
+ 3.4.2
+ 3.2.8
+ 0.12.0
+ 0.8.14
+ 0.80
+ 0.75
+
+ true
+
+
+
+
+
+
+ org.apache.flink
+ flink-core
+ ${flink.version}
+
+
+ org.apache.flink
+ flink-core-api
+ ${flink.version}
+
+
+ org.apache.flink
+ flink-metrics-core
+ ${flink.version}
+
+
+ org.apache.flink
+ flink-annotations
+ ${flink.version}
+
+
+ org.apache.flink
+ flink-connector-base
+ ${flink.version}
+
+
+ org.apache.flink
+ flink-table-common
+ ${flink.version}
+
+
+ org.apache.flink
+ flink-table-api-java
+ ${flink.version}
+
+
+ org.apache.flink
+ flink-table-api-java-bridge
+ ${flink.version}
+
+
+ org.apache.flink
+ flink-table-planner-loader
+ ${flink.version}
+
+
+ org.apache.flink
+ flink-table-runtime
+ ${flink.version}
+
+
+ org.apache.flink
+ flink-connector-datagen
+ ${flink.version}
+
+
+ org.apache.flink
+ flink-runtime
+ ${flink.version}
+
+
+ org.apache.flink
+ flink-clients
+ ${flink.version}
+
+
+ com.influxdb
+ influxdb3-java
+ ${influxdb3.version}
+
+
+ software.amazon.awssdk
+ bom
+ ${aws.sdk.version}
+ pom
+ import
+
+
+ io.grpc
+ grpc-bom
+ ${grpc.version}
+ pom
+ import
+
+
+ io.netty
+ netty-bom
+ ${netty.version}
+ pom
+ import
+
+
+ com.fasterxml.jackson
+ jackson-bom
+ ${jackson.version}
+ pom
+ import
+
+
+ org.testcontainers
+ testcontainers-bom
+ ${testcontainers.version}
+ pom
+ import
+
+
+
+
+
+
+ org.apache.flink
+ flink-core
+ provided
+
+
+ org.apache.flink
+ flink-core-api
+ provided
+
+
+ org.apache.flink
+ flink-metrics-core
+ provided
+
+
+ org.apache.flink
+ flink-annotations
+ provided
+
+
+ org.apache.flink
+ flink-connector-base
+ provided
+
+
+ org.apache.flink
+ flink-table-common
+ provided
+
+
+ org.slf4j
+ slf4j-api
+ ${slf4j.version}
+ provided
+
+
+
+ com.influxdb
+ influxdb3-java
+
+
+
+ org.junit.platform
+ junit-platform-engine
+
+
+ org.junit.platform
+ junit-platform-launcher
+
+
+
+ io.netty
+ netty-tcnative-boringssl-static
+
+
+
+
+ software.amazon.awssdk
+ secretsmanager
+
+
+ software.amazon.awssdk
+ netty-nio-client
+
+
+
+
+ software.amazon.awssdk
+ sdk-core
+
+
+ software.amazon.awssdk
+ aws-core
+
+
+ software.amazon.awssdk
+ regions
+
+
+ com.fasterxml.jackson.core
+ jackson-databind
+
+
+
+ org.junit.jupiter
+ junit-jupiter-api
+ ${junit.version}
+ test
+
+
+ org.junit.jupiter
+ junit-jupiter-params
+ ${junit.version}
+ test
+
+
+ org.junit.jupiter
+ junit-jupiter-engine
+ ${junit.version}
+ test
+
+
+ org.assertj
+ assertj-core
+ ${assertj.version}
+ test
+
+
+ org.wiremock
+ wiremock
+ ${wiremock.version}
+ test
+
+
+ org.testcontainers
+ testcontainers
+ test
+
+
+ org.testcontainers
+ junit-jupiter
+ test
+
+
+ org.apache.flink
+ flink-runtime
+ test
+
+
+ org.apache.flink
+ flink-clients
+ test
+
+
+ org.apache.flink
+ flink-connector-datagen
+ test
+
+
+ org.apache.flink
+ flink-table-api-java
+ test
+
+
+ org.apache.flink
+ flink-table-api-java-bridge
+ test
+
+
+ org.apache.flink
+ flink-table-planner-loader
+ test
+
+
+ org.apache.flink
+ flink-table-runtime
+ test
+
+
+
+
+
+
+ src/main/resources
+
+
+ ${project.basedir}
+ META-INF
+
+ LICENSE
+ NOTICE
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven.compiler.version}
+
+ ${maven.compiler.release}
+ true
+ true
+
+
+
+ org.jacoco
+ jacoco-maven-plugin
+ ${jacoco.version}
+
+
+ prepare-agent
+
+ prepare-agent
+
+
+ jacocoArgLine
+
+
+
+ report
+ test
+
+ report
+
+
+
+ check
+ verify
+
+ check
+
+
+
+
+ BUNDLE
+
+
+ LINE
+ COVEREDRATIO
+ ${jacoco.minimum.line.coverage}
+
+
+ BRANCH
+ COVEREDRATIO
+ ${jacoco.minimum.branch.coverage}
+
+
+
+
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-antrun-plugin
+ ${maven.antrun.version}
+
+
+ generate-test-tls
+ generate-test-resources
+
+ run
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ ${maven.surefire.version}
+
+ false
+ container
+
+ @{jacocoArgLine} --add-opens=java.base/java.nio=ALL-UNNAMED
+
+
+ ${test.tls.dir}/truststore.p12
+ ${test.tls.password}
+ PKCS12
+ ${test.tls.dir}/server.p12
+ ${test.tls.password}
+
+
+
+
+ org.apache.maven.plugins
+ maven-failsafe-plugin
+ ${maven.failsafe.version}
+
+
+
+ integration-test
+ verify
+
+
+
+
+ ${skipITs}
+ false
+
+ @{jacocoArgLine} --add-opens=java.base/java.nio=ALL-UNNAMED
+
+
+ ${test.tls.dir}/truststore.p12
+ ${test.tls.password}
+ PKCS12
+ ${test.tls.dir}/server.p12
+ ${test.tls.password}
+
+
+
+
+ org.apache.maven.plugins
+ maven-jar-plugin
+ ${maven.jar.version}
+
+
+
+ true
+
+
+
+ software.amazon.timestream.influxdb3.flink
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-source-plugin
+ ${maven.source.version}
+
+
+ attach-sources
+
+ jar-no-fork
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-javadoc-plugin
+ ${maven.javadoc.version}
+
+ true
+ all,-missing
+
+ software.amazon.timestream.influxdb3.flink.internal
+
+
+
+
+ attach-javadocs
+
+ jar
+
+
+
+
+
+
+
+
+
+ integration-tests
+
+ false
+
+
+
+
+ release
+
+ false
+
+
+
+
+ org.apache.maven.plugins
+ maven-gpg-plugin
+ ${maven.gpg.version}
+
+
+ sign-artifacts
+ verify
+
+ sign
+
+
+ bc
+
+
+
+
+
+ org.sonatype.central
+ central-publishing-maven-plugin
+ ${central.publishing.version}
+ true
+
+ central
+ ${central.autoPublish}
+ validated
+ ${project.artifactId}-${project.version}
+
+
+
+
+
+
+
diff --git a/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/InfluxDB3Sink.java b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/InfluxDB3Sink.java
new file mode 100644
index 00000000..ff8c7873
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/InfluxDB3Sink.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ */
+package software.amazon.timestream.influxdb3.flink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.connector.sink2.StatefulSinkWriter;
+import org.apache.flink.api.connector.sink2.WriterInitContext;
+import org.apache.flink.connector.base.sink.AsyncSinkBase;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.core.io.SimpleVersionedSerializer;
+
+import software.amazon.timestream.influxdb3.flink.internal.InfluxDBClientFactory;
+import software.amazon.timestream.influxdb3.flink.internal.InfluxDB3SinkConfig;
+import software.amazon.timestream.influxdb3.flink.internal.InfluxDB3SinkWriter;
+import software.amazon.timestream.influxdb3.flink.internal.InfluxDB3WriteRequest;
+import software.amazon.timestream.influxdb3.flink.internal.InfluxDB3WriterStateSerializer;
+import software.amazon.timestream.influxdb3.flink.internal.LineProtocolElementConverter;
+
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Collections;
+
+/**
+ * An at-least-once Flink DataStream sink for Amazon Timestream for InfluxDB 3.
+ *
+ * @param type of records consumed by the sink
+ */
+@PublicEvolving
+public final class InfluxDB3Sink
+ extends AsyncSinkBase {
+ private static final long serialVersionUID = 1L;
+
+ private final InfluxDB3SinkConfig config;
+ private final InfluxDBClientFactory clientFactory;
+
+ InfluxDB3Sink(
+ LineProtocolConverter converter,
+ InfluxDB3SinkConfig config,
+ InfluxDBClientFactory clientFactory) {
+ super(
+ new LineProtocolElementConverter<>(
+ converter,
+ config.isFailOnValidation(),
+ config.isPrintFailedRequests(),
+ config.getMaxRecordSizeInBytes()),
+ config.getMaxBatchSize(),
+ config.getMaxInFlightRequests(),
+ config.getMaxBufferedRequests(),
+ config.getMaxBatchSizeInBytes(),
+ config.getMaxTimeInBufferMillis(),
+ config.getMaxRecordSizeInBytes(),
+ config.getRequestTimeout().toMillis(),
+ config.isFailOnRequestTimeout());
+ this.config = config;
+ this.clientFactory = clientFactory;
+ }
+
+ /**
+ * Creates a sink builder.
+ *
+ * @param type of records consumed by the sink
+ * @return a builder with the documented defaults
+ */
+ public static InfluxDB3SinkBuilder builder() {
+ return new InfluxDB3SinkBuilder<>();
+ }
+
+ InfluxDB3SinkConfig getConfiguration() {
+ return config;
+ }
+
+ @Override
+ public StatefulSinkWriter> createWriter(
+ WriterInitContext context) throws IOException {
+ return restoreWriter(context, Collections.emptyList());
+ }
+
+ @Override
+ public StatefulSinkWriter> restoreWriter(
+ WriterInitContext context,
+ Collection> recoveredState)
+ throws IOException {
+ return new InfluxDB3SinkWriter<>(
+ getElementConverter(), context, config, clientFactory, recoveredState);
+ }
+
+ @Override
+ public SimpleVersionedSerializer>
+ getWriterStateSerializer() {
+ return new InfluxDB3WriterStateSerializer(config.getMaxRecordSizeInBytes());
+ }
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/InfluxDB3SinkBuilder.java b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/InfluxDB3SinkBuilder.java
new file mode 100644
index 00000000..b128c698
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/InfluxDB3SinkBuilder.java
@@ -0,0 +1,826 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ */
+package software.amazon.timestream.influxdb3.flink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.sink.AsyncSinkBaseBuilder;
+
+import com.influxdb.v3.client.write.WritePrecision;
+import software.amazon.timestream.influxdb3.flink.auth.StaticTokenProvider;
+import software.amazon.timestream.influxdb3.flink.auth.TokenProvider;
+import software.amazon.timestream.influxdb3.flink.failure.DefaultWriteFailureHandler;
+import software.amazon.timestream.influxdb3.flink.failure.WriteFailureHandler;
+import software.amazon.timestream.influxdb3.flink.internal.DefaultInfluxDBClientFactory;
+import software.amazon.timestream.influxdb3.flink.internal.InfluxDBClientFactory;
+import software.amazon.timestream.influxdb3.flink.internal.InfluxDB3SinkConfig;
+import software.amazon.timestream.influxdb3.flink.internal.InfluxDB3WriteRequest;
+
+import java.net.URI;
+import java.time.Duration;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.regex.Pattern;
+
+/**
+ * Builder for {@link InfluxDB3Sink}.
+ *
+ * The endpoint, database, token provider, and converter are required. Optional settings and
+ * defaults are documented on their setter methods and exposed through the {@code DEFAULT_*}
+ * constants.
+ *
+ *
Configuration is fully validated when {@link #build()} is called. Setters may reject values
+ * immediately when constructing public value types that enforce their own invariants.
+ *
+ * @param type of records consumed by the sink
+ */
+@PublicEvolving
+public final class InfluxDB3SinkBuilder
+ extends AsyncSinkBaseBuilder<
+ InputT, InfluxDB3WriteRequest, InfluxDB3SinkBuilder> {
+
+ /** Default precision used to interpret line protocol timestamps. */
+ public static final WritePrecision DEFAULT_WRITE_PRECISION = WritePrecision.NS;
+
+ /** Default maximum number of records in one write request. */
+ public static final int DEFAULT_MAX_BATCH_SIZE = 10_000;
+
+ /** Default maximum number of concurrent write requests. */
+ public static final int DEFAULT_MAX_IN_FLIGHT_REQUESTS = 8;
+
+ /** Default maximum number of records buffered by each sink subtask. */
+ public static final int DEFAULT_MAX_BUFFERED_REQUESTS = 20_000;
+
+ /** Default maximum uncompressed size of one write request. */
+ public static final long DEFAULT_MAX_BATCH_SIZE_IN_BYTES = 10L * 1024 * 1024;
+
+ /** Default maximum uncompressed payload bytes buffered by each sink subtask. */
+ public static final long DEFAULT_MAX_BUFFERED_BYTES = 64L * 1024 * 1024;
+
+ /** Default maximum time a record remains buffered before being sent. */
+ public static final long DEFAULT_MAX_TIME_IN_BUFFER_MILLIS = 5_000;
+
+ /** Default maximum uncompressed size of one line protocol record. */
+ public static final long DEFAULT_MAX_RECORD_SIZE_IN_BYTES = 1024L * 1024;
+
+ /** Default number of retries after the initial write attempt. */
+ public static final int DEFAULT_MAX_RETRIES = 8;
+
+ /** Default delay before the first retry. */
+ public static final Duration DEFAULT_INITIAL_RETRY_BACKOFF = Duration.ofMillis(200);
+
+ /** Default upper bound for retry delays, including {@code Retry-After}. */
+ public static final Duration DEFAULT_MAX_RETRY_BACKOFF = Duration.ofSeconds(30);
+
+ /** Default proportional jitter applied to retry delays. */
+ public static final double DEFAULT_RETRY_JITTER = 0.2;
+
+ /** Default timeout for establishing an InfluxDB HTTP connection. */
+ public static final Duration DEFAULT_CONNECTION_TIMEOUT = Duration.ofSeconds(10);
+
+ /** Default hard deadline for one blocking InfluxDB HTTP write attempt. */
+ public static final Duration DEFAULT_WRITE_TIMEOUT = Duration.ofSeconds(10);
+
+ /** Default timeout for Flink to receive a result for one write attempt. */
+ public static final Duration DEFAULT_REQUEST_TIMEOUT = Duration.ofSeconds(60);
+
+ /** Default behavior when a Flink request timeout expires. */
+ public static final boolean DEFAULT_FAIL_ON_REQUEST_TIMEOUT = true;
+
+ /** Default behavior for gzip request compression. */
+ public static final boolean DEFAULT_GZIP_ENABLED = true;
+
+ /** Default behavior for accepting valid rows from a partially invalid batch. */
+ public static final boolean DEFAULT_ACCEPT_PARTIAL = true;
+
+ /** Default behavior for acknowledging writes before durable synchronization. */
+ public static final boolean DEFAULT_NO_SYNC = false;
+
+ /** Default behavior for permanently rejected lines from partial writes. */
+ public static final boolean DEFAULT_FAIL_ON_REJECTED = false;
+
+ /** Default behavior for local and server-side validation failures. */
+ public static final boolean DEFAULT_FAIL_ON_VALIDATION = true;
+
+ /** Default behavior for terminal write errors and retry exhaustion. */
+ public static final boolean DEFAULT_FAIL_ON_ERROR = true;
+
+ /** Default behavior for logging terminally failed line protocol values. */
+ public static final boolean DEFAULT_PRINT_FAILED_REQUESTS = false;
+
+ /** Default behavior for publishing sink metrics to Managed Flink CloudWatch metrics. */
+ public static final boolean DEFAULT_MANAGED_FLINK_METRICS_ENABLED = false;
+
+ private static final Pattern MANAGED_FLINK_METRICS_SINK_NAME_PATTERN =
+ Pattern.compile("[A-Za-z0-9_]{1,255}");
+
+ /**
+ * Minimum margin between {@code requestTimeout} and {@code writeTimeout + maxRetryBackoff}.
+ * Leaves room for a cancellation confirmation wait that is strictly shorter than the margin.
+ */
+ private static final long MIN_REQUEST_TIMEOUT_HEADROOM_MILLIS = 2L;
+
+ private String endpoint;
+ private String database;
+ private TokenProvider tokenProvider;
+ private LineProtocolConverter converter;
+ private WriteFailureHandler failureHandler;
+ private WritePrecision writePrecision = DEFAULT_WRITE_PRECISION;
+ private long maxBufferedBytes = DEFAULT_MAX_BUFFERED_BYTES;
+ private Duration connectionTimeout = DEFAULT_CONNECTION_TIMEOUT;
+ private Duration writeTimeout = DEFAULT_WRITE_TIMEOUT;
+ private Duration requestTimeout = DEFAULT_REQUEST_TIMEOUT;
+ private boolean failOnRequestTimeout = DEFAULT_FAIL_ON_REQUEST_TIMEOUT;
+ private boolean gzipEnabled = DEFAULT_GZIP_ENABLED;
+ private boolean acceptPartial = DEFAULT_ACCEPT_PARTIAL;
+ private boolean noSync = DEFAULT_NO_SYNC;
+ private boolean failOnRejected = DEFAULT_FAIL_ON_REJECTED;
+ private boolean failOnValidation = DEFAULT_FAIL_ON_VALIDATION;
+ private boolean failOnError = DEFAULT_FAIL_ON_ERROR;
+ private boolean printFailedRequests = DEFAULT_PRINT_FAILED_REQUESTS;
+ private boolean failOnRejectedConfigured;
+ private boolean failOnErrorConfigured;
+ private boolean customFailureHandlerConfigured;
+ private int maxRetries = DEFAULT_MAX_RETRIES;
+ private Duration initialRetryBackoff = DEFAULT_INITIAL_RETRY_BACKOFF;
+ private Duration maxRetryBackoff = DEFAULT_MAX_RETRY_BACKOFF;
+ private double retryJitter = DEFAULT_RETRY_JITTER;
+ private boolean managedFlinkMetricsEnabled = DEFAULT_MANAGED_FLINK_METRICS_ENABLED;
+ private String managedFlinkMetricsSinkName;
+ private InfluxDBClientFactory clientFactory = DefaultInfluxDBClientFactory.INSTANCE;
+
+ /** Creates a sink builder with the documented defaults. */
+ public InfluxDB3SinkBuilder() {}
+
+ /**
+ * Sets the base HTTPS endpoint for the InfluxDB 3 cluster.
+ *
+ * Required; there is no default.
+ *
+ *
The endpoint is parsed and validated when {@link #build()} is called.
+ *
+ * @param endpoint cluster endpoint, including its port when required
+ * @return this builder
+ */
+ public InfluxDB3SinkBuilder setEndpoint(String endpoint) {
+ this.endpoint = endpoint;
+ return this;
+ }
+
+ /**
+ * Sets the base HTTPS endpoint for the InfluxDB 3 cluster.
+ *
+ * Required; there is no default.
+ *
+ *
The endpoint is validated when {@link #build()} is called.
+ *
+ * @param endpoint cluster endpoint, including its port when required
+ * @return this builder
+ */
+ public InfluxDB3SinkBuilder setEndpoint(URI endpoint) {
+ this.endpoint = endpoint == null ? null : endpoint.toString();
+ return this;
+ }
+
+ /**
+ * Sets the target InfluxDB 3 database.
+ *
+ * Required; there is no default.
+ *
+ * @param database database name
+ * @return this builder
+ */
+ public InfluxDB3SinkBuilder setDatabase(String database) {
+ this.database = database;
+ return this;
+ }
+
+ /**
+ * Sets a fixed token that will be serialized with the Flink job.
+ *
+ * This is intended for local development. Deployed jobs should use {@link
+ * #setTokenProvider(TokenProvider)}.
+ * Either this method or {@link #setTokenProvider(TokenProvider)} is required.
+ * The token is validated immediately by {@link StaticTokenProvider}.
+ *
+ * @param token InfluxDB API token
+ * @return this builder
+ */
+ public InfluxDB3SinkBuilder setToken(String token) {
+ this.tokenProvider = new StaticTokenProvider(token);
+ return this;
+ }
+
+ /**
+ * Sets the token provider initialized independently in each sink subtask.
+ *
+ * Either this method or {@link #setToken(String)} is required.
+ *
+ * @param tokenProvider serializable token provider
+ * @return this builder
+ */
+ public InfluxDB3SinkBuilder setTokenProvider(TokenProvider tokenProvider) {
+ this.tokenProvider = tokenProvider;
+ return this;
+ }
+
+ /**
+ * Sets the converter that produces one line protocol row per input record.
+ *
+ * Required; there is no default.
+ *
+ * @param converter serializable record converter
+ * @return this builder
+ */
+ public InfluxDB3SinkBuilder setConverter(LineProtocolConverter converter) {
+ this.converter = converter;
+ return this;
+ }
+
+ /**
+ * Sets the policy used to classify record-level write failures.
+ *
+ * A custom handler replaces {@link #setFailOnRejected(boolean)} and {@link
+ * #setFailOnError(boolean)}. Explicitly configuring either of those options together with a
+ * custom handler is invalid. Validation and failed-request logging remain controlled by
+ * {@link #setFailOnValidation(boolean)} and {@link #setPrintFailedRequests(boolean)}.
+ * Connector-internal failures and hard-fatal HTTP responses are not delegated to the handler.
+ * By default, the built-in handler uses {@link #DEFAULT_FAIL_ON_REJECTED} and {@link
+ * #DEFAULT_FAIL_ON_ERROR}.
+ *
+ * @param failureHandler serializable failure handler
+ * @return this builder
+ */
+ public InfluxDB3SinkBuilder setFailureHandler(WriteFailureHandler failureHandler) {
+ this.failureHandler = failureHandler;
+ this.customFailureHandlerConfigured = true;
+ return this;
+ }
+
+ /**
+ * Sets the precision used to interpret timestamps in line protocol records.
+ *
+ * Default: {@link #DEFAULT_WRITE_PRECISION}.
+ *
+ * @param writePrecision timestamp precision
+ * @return this builder
+ */
+ public InfluxDB3SinkBuilder setWritePrecision(WritePrecision writePrecision) {
+ this.writePrecision = writePrecision;
+ return this;
+ }
+
+ /**
+ * Sets the maximum number of line protocol rows in one HTTP request.
+ *
+ * Default: {@link #DEFAULT_MAX_BATCH_SIZE}.
+ *
+ * @param maxBatchSize positive row count
+ * @return this builder
+ */
+ @Override
+ public InfluxDB3SinkBuilder setMaxBatchSize(int maxBatchSize) {
+ return super.setMaxBatchSize(maxBatchSize);
+ }
+
+ /**
+ * Sets the maximum number of concurrent blocking HTTP writes per sink subtask.
+ *
+ * This also determines the number of write executor threads.
+ * Default: {@link #DEFAULT_MAX_IN_FLIGHT_REQUESTS}.
+ *
+ * @param maxInFlightRequests positive request count
+ * @return this builder
+ */
+ @Override
+ public InfluxDB3SinkBuilder setMaxInFlightRequests(int maxInFlightRequests) {
+ return super.setMaxInFlightRequests(maxInFlightRequests);
+ }
+
+ /**
+ * Sets the maximum number of rows buffered by one sink subtask.
+ *
+ * Backpressure is applied when either this limit or {@link #setMaxBufferedBytes(long)}
+ * is reached.
+ * Default: at least {@link #DEFAULT_MAX_BUFFERED_REQUESTS}; when the configured batch size
+ * is larger, one more than that batch size.
+ *
+ * @param maxBufferedRequests positive row count, greater than {@code maxBatchSize}
+ * @return this builder
+ */
+ @Override
+ public InfluxDB3SinkBuilder setMaxBufferedRequests(int maxBufferedRequests) {
+ return super.setMaxBufferedRequests(maxBufferedRequests);
+ }
+
+ /**
+ * Sets the maximum uncompressed payload size of one HTTP request.
+ *
+ * Default: {@link #DEFAULT_MAX_BATCH_SIZE_IN_BYTES} (10 MiB).
+ *
+ * @param maxBatchSizeInBytes positive byte count
+ * @return this builder
+ */
+ @Override
+ public InfluxDB3SinkBuilder setMaxBatchSizeInBytes(long maxBatchSizeInBytes) {
+ return super.setMaxBatchSizeInBytes(maxBatchSizeInBytes);
+ }
+
+ /**
+ * Sets how long the oldest buffered row may wait before a partial batch is sent.
+ *
+ * Default: {@link #DEFAULT_MAX_TIME_IN_BUFFER_MILLIS}.
+ *
+ * @param maxTimeInBufferMS positive duration in milliseconds
+ * @return this builder
+ */
+ @Override
+ public InfluxDB3SinkBuilder setMaxTimeInBufferMS(long maxTimeInBufferMS) {
+ return super.setMaxTimeInBufferMS(maxTimeInBufferMS);
+ }
+
+ /**
+ * Sets the largest accepted uncompressed line protocol row.
+ *
+ * Default: {@link #DEFAULT_MAX_RECORD_SIZE_IN_BYTES} (1 MiB).
+ *
+ * @param maxRecordSizeInBytes positive byte count
+ * @return this builder
+ */
+ @Override
+ public InfluxDB3SinkBuilder setMaxRecordSizeInBytes(long maxRecordSizeInBytes) {
+ return super.setMaxRecordSizeInBytes(maxRecordSizeInBytes);
+ }
+
+ /**
+ * Sets the maximum uncompressed payload bytes buffered by one sink subtask.
+ *
+ * This limit excludes Java object overhead and payload copies owned by in-flight requests.
+ * Default: {@link #DEFAULT_MAX_BUFFERED_BYTES} (64 MiB).
+ *
+ * @param maxBufferedBytes positive byte count, at least {@code maxBatchSizeInBytes}
+ * @return this builder
+ */
+ public InfluxDB3SinkBuilder setMaxBufferedBytes(long maxBufferedBytes) {
+ this.maxBufferedBytes = maxBufferedBytes;
+ return this;
+ }
+
+ /**
+ * Sets the timeout for establishing an InfluxDB HTTP connection.
+ *
+ * The write-attempt deadline remains the outer bound when it is shorter.
+ * Default: {@link #DEFAULT_CONNECTION_TIMEOUT}.
+ *
+ * @param connectionTimeout positive timeout
+ * @return this builder
+ */
+ public InfluxDB3SinkBuilder setConnectionTimeout(Duration connectionTimeout) {
+ this.connectionTimeout = connectionTimeout;
+ return this;
+ }
+
+ /**
+ * Sets the hard deadline for one blocking InfluxDB HTTP write attempt.
+ *
+ * The connector interrupts the official client's blocking call when this deadline expires.
+ * Default: {@link #DEFAULT_WRITE_TIMEOUT}.
+ *
+ * @param writeTimeout positive write timeout
+ * @return this builder
+ */
+ public InfluxDB3SinkBuilder setWriteTimeout(Duration writeTimeout) {
+ this.writeTimeout = writeTimeout;
+ return this;
+ }
+
+ /**
+ * Sets how long Flink waits for a write result, including retry scheduling.
+ *
+ * Default: {@link #DEFAULT_REQUEST_TIMEOUT}.
+ *
+ * @param requestTimeout positive request timeout
+ * @return this builder
+ */
+ public InfluxDB3SinkBuilder setRequestTimeout(Duration requestTimeout) {
+ this.requestTimeout = requestTimeout;
+ return this;
+ }
+
+ /**
+ * Sets whether an expired Flink request timeout fails the sink.
+ *
+ * Default: {@link #DEFAULT_FAIL_ON_REQUEST_TIMEOUT}.
+ *
+ * @param failOnRequestTimeout {@code true} to fail the job on timeout
+ * @return this builder
+ */
+ public InfluxDB3SinkBuilder setFailOnRequestTimeout(boolean failOnRequestTimeout) {
+ this.failOnRequestTimeout = failOnRequestTimeout;
+ return this;
+ }
+
+ /**
+ * Enables or disables gzip request compression.
+ *
+ * Default: {@link #DEFAULT_GZIP_ENABLED}.
+ *
+ * @param gzipEnabled {@code true} to gzip write payloads
+ * @return this builder
+ */
+ public InfluxDB3SinkBuilder setGzipEnabled(boolean gzipEnabled) {
+ this.gzipEnabled = gzipEnabled;
+ return this;
+ }
+
+ /**
+ * Sets whether the server may accept valid rows from a partially invalid batch.
+ *
+ * Default: {@link #DEFAULT_ACCEPT_PARTIAL}.
+ *
+ * @param acceptPartial {@code true} to enable partial writes
+ * @return this builder
+ */
+ public InfluxDB3SinkBuilder setAcceptPartial(boolean acceptPartial) {
+ this.acceptPartial = acceptPartial;
+ return this;
+ }
+
+ /**
+ * Sets whether InfluxDB may acknowledge before synchronizing the write to durable storage.
+ *
+ * Default: {@link #DEFAULT_NO_SYNC}.
+ *
+ * @param noSync {@code true} to reduce durability in favor of write latency
+ * @return this builder
+ */
+ public InfluxDB3SinkBuilder setNoSync(boolean noSync) {
+ this.noSync = noSync;
+ return this;
+ }
+
+ /**
+ * Sets whether a permanently rejected line from a partial write fails the sink.
+ *
+ * When disabled, only the rejected line is dropped. This option configures the built-in
+ * failure handler and cannot be explicitly combined with a custom handler.
+ * Default: {@link #DEFAULT_FAIL_ON_REJECTED}.
+ *
+ * @param failOnRejected {@code true} to fail instead of dropping rejected lines
+ * @return this builder
+ */
+ public InfluxDB3SinkBuilder setFailOnRejected(boolean failOnRejected) {
+ this.failOnRejected = failOnRejected;
+ this.failOnRejectedConfigured = true;
+ return this;
+ }
+
+ /**
+ * Sets whether validation failures fail the sink.
+ *
+ * This covers invalid output from the line protocol converter and non-partial HTTP 400 or
+ * 422 schema or parse failures. When disabled, the invalid record or affected batch is
+ * dropped. This connector-owned policy also applies when a custom failure handler is
+ * configured.
+ * Default: {@link #DEFAULT_FAIL_ON_VALIDATION}.
+ *
+ * @param failOnValidation {@code true} to fail on validation errors
+ * @return this builder
+ */
+ public InfluxDB3SinkBuilder setFailOnValidation(boolean failOnValidation) {
+ this.failOnValidation = failOnValidation;
+ return this;
+ }
+
+ /**
+ * Sets whether terminal write errors fail the sink.
+ *
+ * This applies after retry handling is complete. This option configures the built-in
+ * failure handler and cannot be explicitly combined with a custom handler.
+ * Default: {@link #DEFAULT_FAIL_ON_ERROR}.
+ *
+ * @param failOnError {@code true} to fail instead of dropping affected records
+ * @return this builder
+ */
+ public InfluxDB3SinkBuilder setFailOnError(boolean failOnError) {
+ this.failOnError = failOnError;
+ this.failOnErrorConfigured = true;
+ return this;
+ }
+
+ /**
+ * Sets whether terminally dropped or failed line protocol values are logged.
+ *
+ * Logging is disabled by default because line protocol may contain sensitive tag or field
+ * values. Logged values have control characters escaped and are truncated, but they are not
+ * redacted. This connector-owned option also applies when a custom failure handler is
+ * configured.
+ * Default: {@link #DEFAULT_PRINT_FAILED_REQUESTS}.
+ *
+ * @param printFailedRequests {@code true} to log terminal failed requests
+ * @return this builder
+ */
+ public InfluxDB3SinkBuilder setPrintFailedRequests(boolean printFailedRequests) {
+ this.printFailedRequests = printFailedRequests;
+ return this;
+ }
+
+ /**
+ * Sets the maximum retries after the initial write attempt.
+ *
+ * Default: {@link #DEFAULT_MAX_RETRIES}.
+ *
+ * @param maxRetries non-negative retry count
+ * @return this builder
+ */
+ public InfluxDB3SinkBuilder setMaxRetries(int maxRetries) {
+ this.maxRetries = maxRetries;
+ return this;
+ }
+
+ /**
+ * Sets exponential retry backoff parameters.
+ *
+ * The server's {@code Retry-After} value is honored up to {@code maxBackoff}.
+ * Defaults: {@link #DEFAULT_INITIAL_RETRY_BACKOFF}, {@link
+ * #DEFAULT_MAX_RETRY_BACKOFF}, and {@link #DEFAULT_RETRY_JITTER} jitter.
+ *
+ * @param initialBackoff non-negative delay before the first retry
+ * @param maxBackoff non-negative upper bound for every retry delay
+ * @param jitter proportional jitter from {@code 0.0} to {@code 1.0}
+ * @return this builder
+ */
+ public InfluxDB3SinkBuilder setRetryBackoff(
+ Duration initialBackoff, Duration maxBackoff, double jitter) {
+ this.initialRetryBackoff = initialBackoff;
+ this.maxRetryBackoff = maxBackoff;
+ this.retryJitter = jitter;
+ return this;
+ }
+
+ /**
+ * Sets whether sink metrics are also published to CloudWatch by Amazon Managed Service for
+ * Apache Flink.
+ *
+ * Managed Flink publishes only metrics registered under the {@code KinesisAnalytics}
+ * metric group. When enabled, the sink also registers its operational metrics under {@code
+ * KinesisAnalytics} with the dimension {@code Connector=TimestreamInfluxDB3}, plus
+ * per-second rates and write latency percentiles. Published metrics are billed as
+ * CloudWatch custom metrics. Leave this disabled on other platforms, where the metrics
+ * would be reported twice.
+ * Default: {@link #DEFAULT_MANAGED_FLINK_METRICS_ENABLED}.
+ *
+ * @param managedFlinkMetricsEnabled {@code true} to publish metrics to Managed Flink
+ * CloudWatch metrics
+ * @return this builder
+ */
+ public InfluxDB3SinkBuilder setManagedFlinkMetricsEnabled(
+ boolean managedFlinkMetricsEnabled) {
+ this.managedFlinkMetricsEnabled = managedFlinkMetricsEnabled;
+ return this;
+ }
+
+ /**
+ * Sets the {@code Sink} dimension of metrics published to Managed Flink CloudWatch metrics.
+ *
+ * Set a distinct name for each InfluxDB sink when a job contains more than one, so their
+ * CloudWatch metrics do not combine. Requires {@link #setManagedFlinkMetricsEnabled(boolean)}.
+ * Default: unset, which publishes metrics without a {@code Sink} dimension.
+ *
+ * @param sinkName 1 to 255 letters, digits, or underscores
+ * @return this builder
+ */
+ public InfluxDB3SinkBuilder setManagedFlinkMetricsSinkName(String sinkName) {
+ this.managedFlinkMetricsSinkName = sinkName;
+ return this;
+ }
+
+ InfluxDB3SinkBuilder setClientFactory(InfluxDBClientFactory clientFactory) {
+ this.clientFactory = clientFactory;
+ return this;
+ }
+
+ @Override
+ public InfluxDB3Sink build() {
+ URI resolvedEndpoint = parseEndpoint(endpoint);
+ validateEndpoint(resolvedEndpoint);
+ requireNonBlank(database, "database");
+ Objects.requireNonNull(tokenProvider, "tokenProvider must be configured");
+ Objects.requireNonNull(converter, "converter must be configured");
+ Objects.requireNonNull(writePrecision, "writePrecision");
+ if (customFailureHandlerConfigured) {
+ Objects.requireNonNull(failureHandler, "failureHandler");
+ if (failOnRejectedConfigured || failOnErrorConfigured) {
+ throw new IllegalArgumentException(
+ "A custom failureHandler cannot be combined with explicitly configured "
+ + "failOnRejected or failOnError");
+ }
+ }
+ requirePositiveMillis(connectionTimeout, "connectionTimeout");
+ long writeTimeoutMillis = requirePositiveMillis(writeTimeout, "writeTimeout");
+ long requestTimeoutMillis = requirePositiveMillis(requestTimeout, "requestTimeout");
+ requireNonNegativeMillis(initialRetryBackoff, "initialRetryBackoff");
+ long maxRetryBackoffMillis =
+ requireNonNegativeMillis(maxRetryBackoff, "maxRetryBackoff");
+ if (initialRetryBackoff.compareTo(maxRetryBackoff) > 0) {
+ throw new IllegalArgumentException(
+ "initialRetryBackoff must not exceed maxRetryBackoff");
+ }
+ final long minimumRequestTimeoutMillis;
+ try {
+ minimumRequestTimeoutMillis =
+ Math.addExact(
+ Math.addExact(writeTimeoutMillis, maxRetryBackoffMillis),
+ MIN_REQUEST_TIMEOUT_HEADROOM_MILLIS);
+ } catch (ArithmeticException error) {
+ throw new IllegalArgumentException(
+ "writeTimeout plus maxRetryBackoff exceeds the supported millisecond range",
+ error);
+ }
+ if (requestTimeoutMillis < minimumRequestTimeoutMillis) {
+ throw new IllegalArgumentException(
+ "requestTimeout must exceed writeTimeout plus maxRetryBackoff by at least "
+ + MIN_REQUEST_TIMEOUT_HEADROOM_MILLIS
+ + " ms");
+ }
+ if (!Double.isFinite(retryJitter) || retryJitter < 0.0 || retryJitter > 1.0) {
+ throw new IllegalArgumentException("retryJitter must be between 0.0 and 1.0");
+ }
+ if (maxRetries < 0) {
+ throw new IllegalArgumentException("maxRetries must not be negative");
+ }
+ if (managedFlinkMetricsSinkName != null) {
+ if (!managedFlinkMetricsEnabled) {
+ throw new IllegalArgumentException(
+ "managedFlinkMetricsSinkName requires managedFlinkMetricsEnabled");
+ }
+ if (!MANAGED_FLINK_METRICS_SINK_NAME_PATTERN
+ .matcher(managedFlinkMetricsSinkName)
+ .matches()) {
+ throw new IllegalArgumentException(
+ "managedFlinkMetricsSinkName must contain 1 to 255 letters, digits, "
+ + "or underscores");
+ }
+ }
+
+ int resolvedMaxBatchSize =
+ Optional.ofNullable(getMaxBatchSize()).orElse(DEFAULT_MAX_BATCH_SIZE);
+ int resolvedMaxInFlightRequests =
+ Optional.ofNullable(getMaxInFlightRequests())
+ .orElse(DEFAULT_MAX_IN_FLIGHT_REQUESTS);
+ int resolvedMaxBufferedRequests =
+ Optional.ofNullable(getMaxBufferedRequests())
+ .orElse(
+ Math.max(
+ DEFAULT_MAX_BUFFERED_REQUESTS,
+ resolvedMaxBatchSize + 1));
+ long resolvedMaxBatchSizeInBytes =
+ Optional.ofNullable(getMaxBatchSizeInBytes())
+ .orElse(DEFAULT_MAX_BATCH_SIZE_IN_BYTES);
+ long resolvedMaxTimeInBufferMillis =
+ Optional.ofNullable(getMaxTimeInBufferMS())
+ .orElse(DEFAULT_MAX_TIME_IN_BUFFER_MILLIS);
+ long resolvedMaxRecordSizeInBytes =
+ Optional.ofNullable(getMaxRecordSizeInBytes())
+ .orElse(DEFAULT_MAX_RECORD_SIZE_IN_BYTES);
+
+ requirePositive(resolvedMaxBatchSize, "maxBatchSize");
+ requirePositive(resolvedMaxInFlightRequests, "maxInFlightRequests");
+ requirePositive(resolvedMaxBufferedRequests, "maxBufferedRequests");
+ requirePositive(resolvedMaxBatchSizeInBytes, "maxBatchSizeInBytes");
+ requirePositive(maxBufferedBytes, "maxBufferedBytes");
+ requirePositive(resolvedMaxTimeInBufferMillis, "maxTimeInBufferMillis");
+ requirePositive(resolvedMaxRecordSizeInBytes, "maxRecordSizeInBytes");
+ if (resolvedMaxBufferedRequests <= resolvedMaxBatchSize) {
+ throw new IllegalArgumentException(
+ "maxBufferedRequests must be greater than maxBatchSize");
+ }
+ if (resolvedMaxBatchSizeInBytes < resolvedMaxRecordSizeInBytes) {
+ throw new IllegalArgumentException(
+ "maxBatchSizeInBytes must be at least maxRecordSizeInBytes");
+ }
+ if (maxBufferedBytes < resolvedMaxBatchSizeInBytes) {
+ throw new IllegalArgumentException(
+ "maxBufferedBytes must be at least maxBatchSizeInBytes");
+ }
+
+ WriteFailureHandler resolvedFailureHandler =
+ customFailureHandlerConfigured
+ ? failureHandler
+ : defaultFailureHandler(failOnRejected, failOnError);
+ boolean failOnRetryExhaustion = customFailureHandlerConfigured || failOnError;
+ InfluxDB3SinkConfig config =
+ new InfluxDB3SinkConfig(
+ resolvedEndpoint,
+ database,
+ tokenProvider,
+ resolvedFailureHandler,
+ writePrecision,
+ resolvedMaxBatchSize,
+ resolvedMaxInFlightRequests,
+ resolvedMaxBufferedRequests,
+ resolvedMaxBatchSizeInBytes,
+ maxBufferedBytes,
+ resolvedMaxTimeInBufferMillis,
+ resolvedMaxRecordSizeInBytes,
+ connectionTimeout,
+ writeTimeout,
+ requestTimeout,
+ failOnRequestTimeout,
+ gzipEnabled,
+ acceptPartial,
+ noSync,
+ failOnValidation,
+ failOnRetryExhaustion,
+ printFailedRequests,
+ maxRetries,
+ initialRetryBackoff,
+ maxRetryBackoff,
+ retryJitter,
+ managedFlinkMetricsEnabled,
+ managedFlinkMetricsSinkName);
+ return new InfluxDB3Sink<>(converter, config, clientFactory);
+ }
+
+ private static WriteFailureHandler defaultFailureHandler(
+ boolean failOnRejected, boolean failOnError) {
+ if (failOnRejected == DEFAULT_FAIL_ON_REJECTED
+ && failOnError == DEFAULT_FAIL_ON_ERROR) {
+ return DefaultWriteFailureHandler.INSTANCE;
+ }
+ return new DefaultWriteFailureHandler(failOnRejected, failOnError);
+ }
+
+ private static URI parseEndpoint(String endpoint) {
+ Objects.requireNonNull(endpoint, "endpoint must be configured");
+ try {
+ return URI.create(endpoint);
+ } catch (IllegalArgumentException error) {
+ throw new IllegalArgumentException("endpoint must be a valid URI", error);
+ }
+ }
+
+ private static void validateEndpoint(URI endpoint) {
+ String scheme = endpoint.getScheme();
+ // The token is sent with every request, so plaintext HTTP is never allowed.
+ if (!"https".equalsIgnoreCase(scheme)) {
+ throw new IllegalArgumentException("endpoint scheme must be https");
+ }
+ if (endpoint.getHost() == null) {
+ throw new IllegalArgumentException("endpoint must contain a host");
+ }
+ if (endpoint.getUserInfo() != null
+ || endpoint.getQuery() != null
+ || endpoint.getFragment() != null) {
+ throw new IllegalArgumentException(
+ "endpoint must not contain user info, query parameters, or a fragment");
+ }
+ if (endpoint.getPath() != null
+ && !endpoint.getPath().isEmpty()
+ && !"/".equals(endpoint.getPath())) {
+ throw new IllegalArgumentException("endpoint must not contain an API path");
+ }
+ }
+
+ private static void requireNonBlank(String value, String name) {
+ if (value == null || value.isBlank()) {
+ throw new IllegalArgumentException(name + " must not be blank");
+ }
+ }
+
+ private static long requirePositiveMillis(Duration value, String name) {
+ Objects.requireNonNull(value, name);
+ if (value.isZero() || value.isNegative()) {
+ throw new IllegalArgumentException(name + " must be positive");
+ }
+ long millis = toMillis(value, name);
+ if (millis == 0) {
+ throw new IllegalArgumentException(name + " must be at least 1 millisecond");
+ }
+ return millis;
+ }
+
+ private static long requireNonNegativeMillis(Duration value, String name) {
+ Objects.requireNonNull(value, name);
+ if (value.isNegative()) {
+ throw new IllegalArgumentException(name + " must not be negative");
+ }
+ return toMillis(value, name);
+ }
+
+ private static void requirePositive(long value, String name) {
+ if (value <= 0) {
+ throw new IllegalArgumentException(name + " must be positive");
+ }
+ }
+
+ private static long toMillis(Duration value, String name) {
+ try {
+ return value.toMillis();
+ } catch (ArithmeticException error) {
+ throw new IllegalArgumentException(
+ name + " exceeds the supported millisecond range", error);
+ }
+ }
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/InfluxDB3SinkException.java b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/InfluxDB3SinkException.java
new file mode 100644
index 00000000..d606f9ba
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/InfluxDB3SinkException.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ */
+package software.amazon.timestream.influxdb3.flink;
+
+import org.apache.flink.annotation.PublicEvolving;
+
+/** Fatal connector exception that causes the Flink job to fail. */
+@PublicEvolving
+public class InfluxDB3SinkException extends RuntimeException {
+ private static final long serialVersionUID = 1L;
+
+ /**
+ * Creates a fatal connector exception.
+ *
+ * @param message failure description
+ */
+ public InfluxDB3SinkException(String message) {
+ super(message);
+ }
+
+ /**
+ * Creates a fatal connector exception with its cause.
+ *
+ * @param message failure description
+ * @param cause underlying failure
+ */
+ public InfluxDB3SinkException(String message, Throwable cause) {
+ super(message, cause);
+ }
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/LineProtocolConverter.java b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/LineProtocolConverter.java
new file mode 100644
index 00000000..a0e0dc7c
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/LineProtocolConverter.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ */
+package software.amazon.timestream.influxdb3.flink;
+
+import org.apache.flink.annotation.PublicEvolving;
+
+import java.io.Serializable;
+
+/**
+ * Converts an input record into one InfluxDB line protocol row.
+ *
+ * @param type of record to convert
+ */
+@FunctionalInterface
+@PublicEvolving
+public interface LineProtocolConverter extends Serializable {
+
+ /**
+ * Converts an input record into line protocol.
+ *
+ * The returned value must contain exactly one non-empty line.
+ *
+ * @param element input record
+ * @return one non-empty line protocol row
+ */
+ String toLineProtocol(InputT element);
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/auth/SecretsManagerTokenProvider.java b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/auth/SecretsManagerTokenProvider.java
new file mode 100644
index 00000000..5d386389
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/auth/SecretsManagerTokenProvider.java
@@ -0,0 +1,270 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ */
+package software.amazon.timestream.influxdb3.flink.auth;
+
+import org.apache.flink.annotation.PublicEvolving;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import software.amazon.awssdk.core.SdkBytes;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient;
+import software.amazon.awssdk.services.secretsmanager.SecretsManagerClientBuilder;
+import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest;
+import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse;
+
+import java.io.IOException;
+import java.time.Duration;
+import java.util.Arrays;
+
+/**
+ * Loads an InfluxDB token from AWS Secrets Manager using the default AWS credential provider
+ * chain.
+ *
+ *
The secret can either be the token itself or a JSON object containing the configured field.
+ * The AWS client and resolved token are transient and are created independently in each Flink sink
+ * subtask.
+ *
+ *
The resolved token is retained until {@link #refreshToken()} or {@link #close()} is called.
+ * The connector resolves it when the sink subtask starts and forces a refresh after an
+ * authentication failure; it does not periodically poll Secrets Manager.
+ */
+@PublicEvolving
+public final class SecretsManagerTokenProvider implements TokenProvider {
+ private static final long serialVersionUID = 1L;
+ private static final Duration API_CALL_TIMEOUT = Duration.ofSeconds(30);
+ private static final Duration API_CALL_ATTEMPT_TIMEOUT = Duration.ofSeconds(10);
+ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
+
+ private final String secretId;
+ private final String jsonField;
+ private final String region;
+ private final String versionStage;
+
+ private transient SecretsManagerClient client;
+ private transient char[] cachedToken;
+
+ private SecretsManagerTokenProvider(Builder builder) {
+ this.secretId = requireNonBlank(builder.secretId, "secretId");
+ this.jsonField = blankToNull(builder.jsonField);
+ this.region = blankToNull(builder.region);
+ this.versionStage = blankToNull(builder.versionStage);
+ }
+
+ /** @return a provider builder */
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ /**
+ * Creates a provider for a plain-text secret using default settings.
+ *
+ * @param secretId secret name or ARN
+ * @return a configured provider
+ */
+ public static SecretsManagerTokenProvider fromSecretId(String secretId) {
+ return builder().setSecretId(secretId).build();
+ }
+
+ @Override
+ public synchronized void open() {
+ if (client != null) {
+ return;
+ }
+ SecretsManagerClientBuilder builder = SecretsManagerClient.builder();
+ builder.overrideConfiguration(
+ override ->
+ override
+ .apiCallTimeout(API_CALL_TIMEOUT)
+ .apiCallAttemptTimeout(API_CALL_ATTEMPT_TIMEOUT));
+ if (region != null) {
+ builder.region(Region.of(region));
+ }
+ client = builder.build();
+ }
+
+ @Override
+ public synchronized char[] getToken() throws IOException {
+ if (cachedToken == null) {
+ loadToken();
+ }
+ return Arrays.copyOf(cachedToken, cachedToken.length);
+ }
+
+ @Override
+ public synchronized char[] refreshToken() throws IOException {
+ loadToken();
+ return Arrays.copyOf(cachedToken, cachedToken.length);
+ }
+
+ @Override
+ public synchronized void close() {
+ clearCachedToken();
+ if (client != null) {
+ client.close();
+ client = null;
+ }
+ }
+
+ void setClientForTesting(SecretsManagerClient client) {
+ this.client = client;
+ }
+
+ private void loadToken() throws IOException {
+ clearCachedToken();
+ if (client == null) {
+ open();
+ }
+
+ GetSecretValueRequest.Builder request =
+ GetSecretValueRequest.builder().secretId(secretId);
+ if (versionStage != null) {
+ request.versionStage(versionStage);
+ }
+
+ final GetSecretValueResponse response;
+ try {
+ response = client.getSecretValue(request.build());
+ } catch (RuntimeException e) {
+ throw new IOException("Unable to retrieve the InfluxDB token from Secrets Manager", e);
+ }
+
+ String secret = response.secretString();
+ if (secret == null) {
+ SdkBytes binary = response.secretBinary();
+ if (binary != null) {
+ secret = binary.asUtf8String();
+ }
+ }
+ if (secret == null) {
+ throw new IOException("Secrets Manager returned no SecretString or SecretBinary");
+ }
+
+ String resolved = resolveToken(secret);
+ if (resolved.isBlank()) {
+ throw new IOException("The resolved InfluxDB token is empty");
+ }
+ cachedToken = resolved.toCharArray();
+ }
+
+ private String resolveToken(String secret) throws IOException {
+ if (jsonField == null) {
+ return secret.trim();
+ }
+ try {
+ JsonNode value = OBJECT_MAPPER.readTree(secret).get(jsonField);
+ if (value == null || !value.isTextual()) {
+ throw new IOException(
+ "Secrets Manager secret does not contain textual field '" + jsonField + "'");
+ }
+ return value.textValue().trim();
+ } catch (JsonProcessingException e) {
+ throw new IOException("Unable to parse the Secrets Manager secret as JSON", e);
+ } catch (IOException e) {
+ throw e;
+ } catch (RuntimeException e) {
+ throw new IOException("Unable to parse the Secrets Manager secret as JSON", e);
+ }
+ }
+
+ private void clearCachedToken() {
+ if (cachedToken != null) {
+ Arrays.fill(cachedToken, '\0');
+ cachedToken = null;
+ }
+ }
+
+ private static String blankToNull(String value) {
+ return value == null || value.isBlank() ? null : value;
+ }
+
+ private static String requireNonBlank(String value, String name) {
+ if (value == null || value.isBlank()) {
+ throw new IllegalArgumentException(name + " must not be blank");
+ }
+ return value;
+ }
+
+ @Override
+ public String toString() {
+ return "SecretsManagerTokenProvider{"
+ + "secretId='"
+ + secretId
+ + '\''
+ + ", jsonField='"
+ + jsonField
+ + '\''
+ + ", region='"
+ + region
+ + '\''
+ + ", versionStage='"
+ + versionStage
+ + '\''
+ + '}';
+ }
+
+ /** Builder for {@link SecretsManagerTokenProvider}. */
+ @PublicEvolving
+ public static final class Builder {
+ private String secretId;
+ private String jsonField;
+ private String region;
+ private String versionStage = "AWSCURRENT";
+
+ private Builder() {}
+
+ /**
+ * Sets the secret name or ARN.
+ *
+ * @param secretId secret name or ARN
+ * @return this builder
+ */
+ public Builder setSecretId(String secretId) {
+ this.secretId = secretId;
+ return this;
+ }
+
+ /**
+ * Selects a top-level textual JSON field instead of using the full secret value.
+ *
+ * @param jsonField JSON field name, or {@code null} for a plain-text secret
+ * @return this builder
+ */
+ public Builder setJsonField(String jsonField) {
+ this.jsonField = jsonField;
+ return this;
+ }
+
+ /**
+ * Sets the Secrets Manager region.
+ *
+ *
When omitted, the AWS SDK default region provider chain is used.
+ *
+ * @param region AWS region identifier
+ * @return this builder
+ */
+ public Builder setRegion(String region) {
+ this.region = region;
+ return this;
+ }
+
+ /**
+ * Sets the Secrets Manager version stage.
+ *
+ * @param versionStage version stage, defaulting to {@code AWSCURRENT}
+ * @return this builder
+ */
+ public Builder setVersionStage(String versionStage) {
+ this.versionStage = versionStage;
+ return this;
+ }
+
+ /** @return a validated token provider */
+ public SecretsManagerTokenProvider build() {
+ return new SecretsManagerTokenProvider(this);
+ }
+ }
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/auth/StaticTokenProvider.java b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/auth/StaticTokenProvider.java
new file mode 100644
index 00000000..b1cd7624
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/auth/StaticTokenProvider.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ */
+package software.amazon.timestream.influxdb3.flink.auth;
+
+import org.apache.flink.annotation.PublicEvolving;
+
+import java.util.Arrays;
+import java.util.Objects;
+
+/**
+ * A serializable, fixed token provider intended for local development and tests.
+ *
+ *
Production jobs should use a provider backed by a secret store.
+ *
+ *
The retained token copy is cleared when {@link #close()} is called.
+ */
+@PublicEvolving
+public final class StaticTokenProvider implements TokenProvider {
+ private static final long serialVersionUID = 1L;
+
+ private final char[] token;
+
+ /**
+ * Creates a provider from a fixed token string.
+ *
+ * @param token non-blank InfluxDB API token
+ */
+ public StaticTokenProvider(String token) {
+ this(Objects.requireNonNull(token, "token").toCharArray());
+ }
+
+ /**
+ * Creates a provider by copying a fixed token array.
+ *
+ * @param token non-blank InfluxDB API token
+ */
+ public StaticTokenProvider(char[] token) {
+ Objects.requireNonNull(token, "token");
+ if (token.length == 0 || isBlank(token)) {
+ throw new IllegalArgumentException("token must not be blank");
+ }
+ this.token = Arrays.copyOf(token, token.length);
+ }
+
+ @Override
+ public synchronized char[] getToken() {
+ return Arrays.copyOf(token, token.length);
+ }
+
+ @Override
+ public synchronized void close() {
+ Arrays.fill(token, '\0');
+ }
+
+ @Override
+ public String toString() {
+ return "StaticTokenProvider{token=[REDACTED]}";
+ }
+
+ private static boolean isBlank(char[] value) {
+ for (char character : value) {
+ if (!Character.isWhitespace(character)) {
+ return false;
+ }
+ }
+ return true;
+ }
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/auth/TokenProvider.java b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/auth/TokenProvider.java
new file mode 100644
index 00000000..f597964b
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/auth/TokenProvider.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ */
+package software.amazon.timestream.influxdb3.flink.auth;
+
+import org.apache.flink.annotation.PublicEvolving;
+
+import java.io.IOException;
+import java.io.Serializable;
+
+/**
+ * Supplies authentication tokens to a sink writer.
+ *
+ *
Implementations are serialized with the Flink job. They must not serialize a resolved token
+ * unless explicitly intended, as with {@link StaticTokenProvider}.
+ */
+@PublicEvolving
+public interface TokenProvider extends Serializable, AutoCloseable {
+
+ /**
+ * Initializes transient resources inside the sink subtask.
+ *
+ * @throws IOException when provider initialization fails
+ */
+ default void open() throws IOException {}
+
+ /**
+ * Returns the current token. The caller owns and clears the returned array.
+ *
+ * @return a new mutable token array
+ * @throws IOException when the token cannot be resolved
+ */
+ char[] getToken() throws IOException;
+
+ /**
+ * Forces a token refresh after an authentication failure.
+ *
+ * @return a new mutable token array
+ * @throws IOException when the token cannot be refreshed
+ */
+ default char[] refreshToken() throws IOException {
+ return getToken();
+ }
+
+ /** Releases transient resources. */
+ @Override
+ default void close() throws IOException {}
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/failure/DefaultWriteFailureHandler.java b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/failure/DefaultWriteFailureHandler.java
new file mode 100644
index 00000000..2587e3c5
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/failure/DefaultWriteFailureHandler.java
@@ -0,0 +1,104 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ */
+package software.amazon.timestream.influxdb3.flink.failure;
+
+import org.apache.flink.annotation.PublicEvolving;
+
+import java.io.EOFException;
+import java.net.ProtocolException;
+import java.net.SocketException;
+import java.net.SocketTimeoutException;
+import java.net.UnknownHostException;
+import java.net.http.HttpTimeoutException;
+import javax.net.ssl.SSLHandshakeException;
+import javax.net.ssl.SSLPeerUnverifiedException;
+
+/**
+ * Default failure classification for the InfluxDB v3 write endpoint.
+ *
+ *
The built-in policy retries explicitly transient HTTP responses and recognized network
+ * failures. TLS handshake, peer verification, HTTP protocol, and unclassified I/O failures use
+ * the configured terminal-error policy.
+ */
+@PublicEvolving
+public final class DefaultWriteFailureHandler implements WriteFailureHandler {
+ private static final long serialVersionUID = 1L;
+
+ /** Shared stateless handler instance. */
+ public static final DefaultWriteFailureHandler INSTANCE =
+ new DefaultWriteFailureHandler(false, true);
+
+ private final boolean failOnRejected;
+ private final boolean failOnError;
+
+ /**
+ * Creates the built-in failure policy.
+ *
+ * @param failOnRejected whether partial-write line rejections fail the sink
+ * @param failOnError whether other terminal errors fail the sink
+ */
+ public DefaultWriteFailureHandler(boolean failOnRejected, boolean failOnError) {
+ this.failOnRejected = failOnRejected;
+ this.failOnError = failOnError;
+ }
+
+ @Override
+ public FailureAction onFailure(WriteFailure failure) {
+ if (failure.isPartialWrite()) {
+ return failOnRejected ? FailureAction.FAIL : FailureAction.DROP;
+ }
+
+ if (failure.getStatusCode().isPresent()) {
+ int status = failure.getStatusCode().getAsInt();
+ if (isRetryableHttpStatus(status)) {
+ return FailureAction.RETRY;
+ }
+ if (status == 401 || status == 403 || status == 413) {
+ return FailureAction.FAIL;
+ }
+ return failOnError ? FailureAction.FAIL : FailureAction.DROP;
+ }
+
+ if (isRetryableTransportFailure(failure.getCause())) {
+ return FailureAction.RETRY;
+ }
+ return failOnError ? FailureAction.FAIL : FailureAction.DROP;
+ }
+
+ private static boolean isRetryableHttpStatus(int status) {
+ return status == 408
+ || status == 425
+ || status == 429
+ || status == 500
+ || status == 502
+ || status == 503
+ || status == 504;
+ }
+
+ private static boolean isRetryableTransportFailure(Throwable error) {
+ boolean retryable = false;
+ Throwable current = error;
+ while (current != null) {
+ if (current instanceof SSLHandshakeException
+ || current instanceof SSLPeerUnverifiedException
+ || current instanceof ProtocolException) {
+ return false;
+ }
+ if (current instanceof SocketException
+ || current instanceof SocketTimeoutException
+ || current instanceof HttpTimeoutException
+ || current instanceof UnknownHostException
+ || current instanceof EOFException) {
+ retryable = true;
+ }
+ Throwable cause = current.getCause();
+ if (cause == null || cause == current) {
+ break;
+ }
+ current = cause;
+ }
+ return retryable;
+ }
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/failure/FailureAction.java b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/failure/FailureAction.java
new file mode 100644
index 00000000..5cf08e6a
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/failure/FailureAction.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ */
+package software.amazon.timestream.influxdb3.flink.failure;
+
+import org.apache.flink.annotation.PublicEvolving;
+
+/** Action to take for a failed InfluxDB write. */
+@PublicEvolving
+public enum FailureAction {
+ /** Retry the failed record subject to the configured retry limit. */
+ RETRY,
+
+ /** Drop the failed record and allow processing to continue. */
+ DROP,
+
+ /** Fail the sink and the containing Flink job. */
+ FAIL
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/failure/WriteFailure.java b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/failure/WriteFailure.java
new file mode 100644
index 00000000..7c1cddc8
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/failure/WriteFailure.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ */
+package software.amazon.timestream.influxdb3.flink.failure;
+
+import org.apache.flink.annotation.PublicEvolving;
+
+import java.util.OptionalInt;
+
+/** Information available to a {@link WriteFailureHandler}. */
+@PublicEvolving
+public final class WriteFailure {
+ private final String lineProtocol;
+ private final Throwable cause;
+ private final int attempt;
+ private final Integer statusCode;
+ private final boolean partialWrite;
+ private final String serverMessage;
+
+ /**
+ * Creates immutable failure details.
+ *
+ * @param lineProtocol rejected line protocol row
+ * @param cause client or server failure
+ * @param attempt zero-based retry attempt
+ * @param statusCode HTTP status code, or {@code null} for a transport failure
+ * @param partialWrite whether valid rows in the same batch were accepted
+ * @param serverMessage line-level server message when available
+ */
+ public WriteFailure(
+ String lineProtocol,
+ Throwable cause,
+ int attempt,
+ Integer statusCode,
+ boolean partialWrite,
+ String serverMessage) {
+ this.lineProtocol = lineProtocol;
+ this.cause = cause;
+ this.attempt = attempt;
+ this.statusCode = statusCode;
+ this.partialWrite = partialWrite;
+ this.serverMessage = serverMessage;
+ }
+
+ /** @return rejected line protocol row */
+ public String getLineProtocol() {
+ return lineProtocol;
+ }
+
+ /** @return client or server failure */
+ public Throwable getCause() {
+ return cause;
+ }
+
+ /** @return zero-based retry attempt for this record */
+ public int getAttempt() {
+ return attempt;
+ }
+
+ /** @return HTTP status code when the failure came from an HTTP response */
+ public OptionalInt getStatusCode() {
+ return statusCode == null ? OptionalInt.empty() : OptionalInt.of(statusCode);
+ }
+
+ /** @return whether valid rows in the same batch were accepted */
+ public boolean isPartialWrite() {
+ return partialWrite;
+ }
+
+ /** @return line-level server message when available */
+ public String getServerMessage() {
+ return serverMessage;
+ }
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/failure/WriteFailureHandler.java b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/failure/WriteFailureHandler.java
new file mode 100644
index 00000000..2087b356
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/failure/WriteFailureHandler.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ */
+package software.amazon.timestream.influxdb3.flink.failure;
+
+import org.apache.flink.annotation.PublicEvolving;
+
+import java.io.Serializable;
+
+/**
+ * Classifies a failed write as retryable, droppable, or fatal.
+ *
+ *
The connector serializes callbacks for each sink writer subtask. Implementations should
+ * return promptly and must not perform long-running or blocking external I/O because callbacks
+ * execute on connector write threads.
+ */
+@FunctionalInterface
+@PublicEvolving
+public interface WriteFailureHandler extends Serializable {
+
+ /**
+ * Classifies one failed line protocol record.
+ *
+ *
Calls are serialized for a given sink writer, but separate subtasks may invoke their own
+ * deserialized handler instances concurrently.
+ *
+ * @param failure failure details
+ * @return action for the failed record
+ */
+ FailureAction onFailure(WriteFailure failure);
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/internal/BlockingWriteExecutor.java b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/internal/BlockingWriteExecutor.java
new file mode 100644
index 00000000..fa542fb0
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/internal/BlockingWriteExecutor.java
@@ -0,0 +1,531 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ */
+package software.amazon.timestream.influxdb3.flink.internal;
+
+import software.amazon.timestream.influxdb3.flink.InfluxDB3SinkException;
+
+import java.net.http.HttpTimeoutException;
+import java.time.Duration;
+import java.util.List;
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.FutureTask;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.ScheduledThreadPoolExecutor;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+
+/** Executes blocking writes with bounded concurrency and independently enforced deadlines. */
+final class BlockingWriteExecutor {
+ private static final long MIN_CANCELLATION_CONFIRMATION_MILLIS = 1L;
+ private static final long MAX_CANCELLATION_CONFIRMATION_MILLIS = 1_000L;
+ private static final AtomicInteger POOL_SEQUENCE = new AtomicInteger();
+
+ private final InfluxDB3SinkConfig config;
+ private final InfluxDBClientManager clientManager;
+ private final InfluxDBSinkMetrics metrics;
+ private final ThreadPoolExecutor writeExecutor;
+ private final ScheduledThreadPoolExecutor timeoutScheduler;
+ private final ScheduledThreadPoolExecutor retryScheduler;
+ private final long cancellationConfirmationMillis;
+
+ BlockingWriteExecutor(
+ InfluxDB3SinkConfig config,
+ InfluxDBClientManager clientManager,
+ InfluxDBSinkMetrics metrics) {
+ this.config = config;
+ this.clientManager = clientManager;
+ this.metrics = metrics;
+ this.cancellationConfirmationMillis = cancellationConfirmationMillis(config);
+
+ int poolId = POOL_SEQUENCE.incrementAndGet();
+ this.writeExecutor =
+ new ThreadPoolExecutor(
+ config.getMaxInFlightRequests(),
+ config.getMaxInFlightRequests(),
+ 0L,
+ TimeUnit.MILLISECONDS,
+ new ArrayBlockingQueue<>(config.getMaxInFlightRequests()),
+ namedDaemonThreadFactory("influxdb3-write-" + poolId + "-"),
+ new ThreadPoolExecutor.AbortPolicy());
+ this.timeoutScheduler =
+ new ScheduledThreadPoolExecutor(
+ config.getMaxInFlightRequests(),
+ namedDaemonThreadFactory("influxdb3-timeout-" + poolId + "-"));
+ configureScheduler(timeoutScheduler);
+ this.retryScheduler =
+ new ScheduledThreadPoolExecutor(
+ 1, namedDaemonThreadFactory("influxdb3-retry-" + poolId + "-"));
+ configureScheduler(retryScheduler);
+ }
+
+ void submit(
+ List requestEntries,
+ List records,
+ SingleCompletionResultHandler resultHandler,
+ WriteFailureCallback failureCallback) {
+ long payloadSizeInBytes = metrics.batchSubmitted(records);
+
+ final InfluxDBClientManager.ClientLease client;
+ try {
+ client = clientManager.acquire();
+ } catch (RuntimeException error) {
+ resultHandler.completeExceptionally(
+ new InfluxDB3SinkException(
+ "Unable to acquire the active InfluxDB client", error));
+ return;
+ }
+
+ WriteAttempt attempt =
+ new WriteAttempt(
+ client,
+ requestEntries,
+ records,
+ resultHandler,
+ failureCallback,
+ payloadSizeInBytes,
+ System.nanoTime());
+ metrics.writeRequestStarted();
+ try {
+ ScheduledFuture> timeoutFuture =
+ timeoutScheduler.schedule(
+ attempt::timeout,
+ config.getWriteTimeout().toMillis(),
+ TimeUnit.MILLISECONDS);
+ attempt.setTimeoutFuture(timeoutFuture);
+ } catch (RejectedExecutionException error) {
+ attempt.abort(
+ new InfluxDB3SinkException(
+ "InfluxDB write timeout could not be scheduled", error));
+ return;
+ }
+ try {
+ writeExecutor.execute(attempt.task);
+ } catch (RejectedExecutionException error) {
+ attempt.abort(
+ new InfluxDB3SinkException(
+ "InfluxDB write executor rejected a request", error));
+ }
+ }
+
+ void scheduleRetry(
+ List retry,
+ Duration delay,
+ SingleCompletionResultHandler resultHandler) {
+ retryScheduler.schedule(
+ () -> resultHandler.retryForEntries(retry),
+ delay.toMillis(),
+ TimeUnit.MILLISECONDS);
+ }
+
+ /**
+ * Shuts down all executors against one shared requestTimeout deadline. Each executor may
+ * additionally wait up to the cancellation confirmation period after forced shutdown.
+ */
+ Exception close() {
+ long closeDeadlineNanos =
+ System.nanoTime()
+ + TimeUnit.MILLISECONDS.toNanos(config.getRequestTimeout().toMillis());
+ writeExecutor.shutdown();
+ boolean terminated = false;
+ Exception failure = null;
+ try {
+ terminated =
+ writeExecutor.awaitTermination(
+ remainingNanos(closeDeadlineNanos), TimeUnit.NANOSECONDS);
+ } catch (InterruptedException error) {
+ Thread.currentThread().interrupt();
+ failure = error;
+ }
+ if (!terminated) {
+ writeExecutor.shutdownNow();
+ if (failure == null) {
+ try {
+ terminated =
+ writeExecutor.awaitTermination(
+ cancellationConfirmationMillis, TimeUnit.MILLISECONDS);
+ } catch (InterruptedException error) {
+ Thread.currentThread().interrupt();
+ failure = error;
+ }
+ }
+ if (!terminated && failure == null) {
+ failure =
+ new InfluxDB3SinkException(
+ "InfluxDB write executor did not terminate after cancellation");
+ }
+ }
+
+ failure =
+ closeScheduler(
+ timeoutScheduler,
+ closeDeadlineNanos,
+ cancellationConfirmationMillis,
+ "timeout",
+ failure);
+ failure =
+ closeScheduler(
+ retryScheduler,
+ closeDeadlineNanos,
+ cancellationConfirmationMillis,
+ "retry",
+ failure);
+ return failure;
+ }
+
+ void shutdownImmediately() {
+ writeExecutor.shutdownNow();
+ timeoutScheduler.shutdownNow();
+ retryScheduler.shutdownNow();
+ }
+
+ @FunctionalInterface
+ interface WriteFailureCallback {
+ void handle(
+ InfluxDBClientManager.ClientGeneration client,
+ List requests,
+ Exception error,
+ SingleCompletionResultHandler resultHandler);
+ }
+
+ private enum WriteAttemptState {
+ PENDING,
+ COMPLETED,
+ TIMED_OUT,
+ ABORTED
+ }
+
+ private final class WriteAttempt {
+ private final InfluxDBClientManager.ClientLease client;
+ private final List requestEntries;
+ private final List records;
+ private final SingleCompletionResultHandler resultHandler;
+ private final WriteFailureCallback failureCallback;
+ private final long payloadSizeInBytes;
+ private final long startNanos;
+ private final TrackedWriteTask task;
+ private final AtomicReference state =
+ new AtomicReference<>(WriteAttemptState.PENDING);
+ private final AtomicBoolean timeoutOutcomeResolved = new AtomicBoolean();
+ private final AtomicBoolean resourcesReleased = new AtomicBoolean();
+ private final AtomicReference> timeoutFuture = new AtomicReference<>();
+ private final AtomicReference> cancellationCheckFuture =
+ new AtomicReference<>();
+
+ private WriteAttempt(
+ InfluxDBClientManager.ClientLease client,
+ List requestEntries,
+ List records,
+ SingleCompletionResultHandler resultHandler,
+ WriteFailureCallback failureCallback,
+ long payloadSizeInBytes,
+ long startNanos) {
+ this.client = client;
+ this.requestEntries = requestEntries;
+ this.records = records;
+ this.resultHandler = resultHandler;
+ this.failureCallback = failureCallback;
+ this.payloadSizeInBytes = payloadSizeInBytes;
+ this.startNanos = startNanos;
+ this.task = new TrackedWriteTask(this::execute);
+ }
+
+ private void setTimeoutFuture(ScheduledFuture> scheduledTimeout) {
+ timeoutFuture.set(scheduledTimeout);
+ if (state.get() != WriteAttemptState.PENDING) {
+ scheduledTimeout.cancel(false);
+ }
+ }
+
+ private void execute() {
+ Exception failure = null;
+ Throwable fatalFailure = null;
+ try {
+ client.client().writeRecords(records);
+ } catch (Exception error) {
+ failure = error;
+ } catch (Throwable error) {
+ fatalFailure = error;
+ }
+
+ if (!state.compareAndSet(
+ WriteAttemptState.PENDING, WriteAttemptState.COMPLETED)) {
+ return;
+ }
+ cancelTimeout();
+ metrics.writeFinished(startNanos);
+ if (fatalFailure != null) {
+ metrics.recordsSendErrors(requestEntries.size());
+ resultHandler.completeExceptionally(
+ new InfluxDB3SinkException(
+ "Unexpected error from the InfluxDB write client", fatalFailure));
+ } else if (failure == null) {
+ metrics.recordsWritten(requestEntries.size());
+ metrics.bytesWritten(payloadSizeInBytes);
+ resultHandler.complete();
+ } else {
+ metrics.writeAttemptFailed(failure);
+ failureCallback.handle(
+ client.generation(), requestEntries, failure, resultHandler);
+ }
+ }
+
+ private void timeout() {
+ if (!state.compareAndSet(
+ WriteAttemptState.PENDING, WriteAttemptState.TIMED_OUT)) {
+ return;
+ }
+ metrics.writeTimeout();
+ metrics.writeFinished(startNanos);
+ boolean cancellationAccepted = task.cancel(true);
+ if (cancellationAccepted && !task.hasRunEntered()) {
+ writeExecutor.remove(task);
+ releaseResources();
+ completeConfirmedTimeout();
+ return;
+ }
+ if (task.hasRunExited()) {
+ completeConfirmedTimeout();
+ return;
+ }
+ scheduleCancellationCheck();
+ }
+
+ private void abort(Exception error) {
+ if (!state.compareAndSet(
+ WriteAttemptState.PENDING, WriteAttemptState.ABORTED)) {
+ return;
+ }
+ cancelTimeout();
+ cancelCancellationCheck();
+ boolean cancellationAccepted = task.cancel(true);
+ if (cancellationAccepted && !task.hasRunEntered()) {
+ writeExecutor.remove(task);
+ releaseResources();
+ } else if (task.hasRunExited()) {
+ releaseResources();
+ }
+ metrics.writeFinished(startNanos);
+ resultHandler.completeExceptionally(error);
+ }
+
+ private void scheduleCancellationCheck() {
+ try {
+ ScheduledFuture> scheduledCheck =
+ timeoutScheduler.schedule(
+ this::verifyCancellation,
+ cancellationConfirmationMillis,
+ TimeUnit.MILLISECONDS);
+ cancellationCheckFuture.set(scheduledCheck);
+ if (timeoutOutcomeResolved.get()) {
+ scheduledCheck.cancel(false);
+ }
+ } catch (RejectedExecutionException error) {
+ if (task.hasRunExited()) {
+ completeConfirmedTimeout();
+ } else {
+ completeUnconfirmedTimeout(error);
+ }
+ }
+ }
+
+ private void verifyCancellation() {
+ if (task.hasRunExited()) {
+ completeConfirmedTimeout();
+ } else {
+ completeUnconfirmedTimeout(null);
+ }
+ }
+
+ private void onTaskExited() {
+ releaseResources();
+ if (state.get() == WriteAttemptState.TIMED_OUT) {
+ completeConfirmedTimeout();
+ }
+ }
+
+ private void completeConfirmedTimeout() {
+ if (!timeoutOutcomeResolved.compareAndSet(false, true)) {
+ return;
+ }
+ cancelCancellationCheck();
+ failureCallback.handle(
+ client.generation(),
+ requestEntries,
+ writeTimeoutException(),
+ resultHandler);
+ }
+
+ private void completeUnconfirmedTimeout(Exception verificationError) {
+ if (task.hasRunExited()) {
+ completeConfirmedTimeout();
+ return;
+ }
+ if (!timeoutOutcomeResolved.compareAndSet(false, true)) {
+ return;
+ }
+ metrics.recordsSendErrors(requestEntries.size());
+ InfluxDB3SinkException failure =
+ new InfluxDB3SinkException(
+ "InfluxDB write exceeded "
+ + config.getWriteTimeout()
+ + " and did not terminate within "
+ + cancellationConfirmationMillis
+ + " ms after cancellation",
+ writeTimeoutException());
+ if (verificationError != null) {
+ failure.addSuppressed(verificationError);
+ }
+ resultHandler.completeExceptionally(failure);
+ }
+
+ private HttpTimeoutException writeTimeoutException() {
+ return new HttpTimeoutException(
+ "InfluxDB write exceeded " + config.getWriteTimeout());
+ }
+
+ private void cancelTimeout() {
+ ScheduledFuture> scheduledTimeout = timeoutFuture.get();
+ if (scheduledTimeout != null) {
+ scheduledTimeout.cancel(false);
+ }
+ }
+
+ private void cancelCancellationCheck() {
+ ScheduledFuture> scheduledCheck = cancellationCheckFuture.get();
+ if (scheduledCheck != null) {
+ scheduledCheck.cancel(false);
+ }
+ }
+
+ private void releaseResources() {
+ if (!resourcesReleased.compareAndSet(false, true)) {
+ return;
+ }
+ metrics.writeRequestFinished();
+ client.release();
+ }
+
+ private final class TrackedWriteTask extends FutureTask {
+ private final AtomicBoolean runEntered = new AtomicBoolean();
+ private final AtomicBoolean runExited = new AtomicBoolean();
+
+ private TrackedWriteTask(Runnable command) {
+ super(command, null);
+ }
+
+ @Override
+ public void run() {
+ runEntered.set(true);
+ try {
+ super.run();
+ } finally {
+ runExited.set(true);
+ onTaskExited();
+ }
+ }
+
+ private boolean hasRunEntered() {
+ return runEntered.get();
+ }
+
+ private boolean hasRunExited() {
+ return runExited.get();
+ }
+ }
+ }
+
+ // Flink's requestTimeout must cover writeTimeout + cancellation confirmation + retry backoff.
+ // The confirmation wait gets strictly less than half of the remaining headroom; the rest is
+ // slack for scheduler and thread jitter so Flink's deadline never fires before ours resolves.
+ // The builder guarantees at least 2 ms of headroom, so the 1 ms minimum still fits.
+ private static long cancellationConfirmationMillis(InfluxDB3SinkConfig config) {
+ long headroomMillis =
+ config.getRequestTimeout().toMillis()
+ - config.getWriteTimeout().toMillis()
+ - config.getMaxRetryBackoff().toMillis();
+ long confirmationMillis =
+ Math.max(
+ MIN_CANCELLATION_CONFIRMATION_MILLIS,
+ (headroomMillis - 1L) / 2L);
+ return Math.min(MAX_CANCELLATION_CONFIRMATION_MILLIS, confirmationMillis);
+ }
+
+ private static void configureScheduler(ScheduledThreadPoolExecutor scheduler) {
+ scheduler.setRemoveOnCancelPolicy(true);
+ scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(true);
+ }
+
+ private static Exception closeScheduler(
+ ScheduledThreadPoolExecutor scheduler,
+ long closeDeadlineNanos,
+ long confirmationMillis,
+ String schedulerName,
+ Exception failure) {
+ scheduler.shutdown();
+ boolean terminated = scheduler.isTerminated();
+ if (!terminated && !Thread.currentThread().isInterrupted()) {
+ try {
+ terminated =
+ scheduler.awaitTermination(
+ remainingNanos(closeDeadlineNanos), TimeUnit.NANOSECONDS);
+ } catch (InterruptedException error) {
+ Thread.currentThread().interrupt();
+ failure = appendFailure(failure, error);
+ }
+ }
+ if (!terminated) {
+ // Forced shutdown only counts as a failure if it dropped queued work or a running
+ // callback did not stop; an idle scheduler may still be retiring its threads.
+ boolean droppedWork = !scheduler.shutdownNow().isEmpty();
+ if (!droppedWork && !Thread.currentThread().isInterrupted()) {
+ try {
+ terminated =
+ scheduler.awaitTermination(
+ confirmationMillis, TimeUnit.MILLISECONDS);
+ } catch (InterruptedException error) {
+ Thread.currentThread().interrupt();
+ failure = appendFailure(failure, error);
+ }
+ }
+ if (!terminated && !Thread.currentThread().isInterrupted()) {
+ failure =
+ appendFailure(
+ failure,
+ new InfluxDB3SinkException(
+ "InfluxDB "
+ + schedulerName
+ + " scheduler did not terminate "
+ + "before its close timeout"));
+ }
+ }
+ return failure;
+ }
+
+ private static long remainingNanos(long deadlineNanos) {
+ return Math.max(0L, deadlineNanos - System.nanoTime());
+ }
+
+ private static Exception appendFailure(Exception failure, Exception additionalFailure) {
+ if (failure == null) {
+ return additionalFailure;
+ }
+ failure.addSuppressed(additionalFailure);
+ return failure;
+ }
+
+ private static ThreadFactory namedDaemonThreadFactory(String prefix) {
+ AtomicInteger sequence = new AtomicInteger();
+ return runnable -> {
+ Thread thread = new Thread(runnable, prefix + sequence.incrementAndGet());
+ thread.setDaemon(true);
+ return thread;
+ };
+ }
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/internal/DefaultInfluxDBClientFactory.java b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/internal/DefaultInfluxDBClientFactory.java
new file mode 100644
index 00000000..bfc70342
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/internal/DefaultInfluxDBClientFactory.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ */
+package software.amazon.timestream.influxdb3.flink.internal;
+
+import org.apache.flink.annotation.Internal;
+
+import com.influxdb.v3.client.InfluxDBClient;
+import com.influxdb.v3.client.config.ClientConfig;
+import com.influxdb.v3.client.write.WriteOptions;
+
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Objects;
+import java.util.function.Function;
+
+/** Production client factory backed by {@code influxdb3-java}. */
+@Internal
+public enum DefaultInfluxDBClientFactory implements InfluxDBClientFactory {
+ INSTANCE;
+
+ @Override
+ public InfluxDBWriteClient create(InfluxDB3SinkConfig config, char[] token) {
+ return create(config, token, InfluxDBClient::getInstance);
+ }
+
+ InfluxDBWriteClient create(
+ InfluxDB3SinkConfig config,
+ char[] token,
+ Function clientCreator) {
+ char[] clientToken = Arrays.copyOf(token, token.length);
+ try {
+ Duration clientTimeout =
+ config.getConnectionTimeout().compareTo(config.getWriteTimeout()) <= 0
+ ? config.getConnectionTimeout()
+ : config.getWriteTimeout();
+ ClientConfig clientConfig =
+ new ClientConfig.Builder()
+ .host(config.getEndpoint().toString())
+ .token(clientToken)
+ .authScheme("Bearer")
+ // influxdb3-java 1.10.0 applies this only as
+ // HttpClient.connectTimeout.
+ .writeTimeout(clientTimeout)
+ .build();
+ WriteOptions writeOptions =
+ new WriteOptions.Builder()
+ .database(config.getDatabase())
+ .precision(config.getWritePrecision())
+ .gzipThreshold(config.isGzipEnabled() ? 0 : Integer.MAX_VALUE)
+ .noSync(config.isNoSync())
+ .acceptPartial(config.isAcceptPartial())
+ .useV2Api(false)
+ .build();
+ InfluxDBClient client =
+ Objects.requireNonNull(
+ clientCreator.apply(clientConfig),
+ "clientCreator returned null");
+ return new OfficialInfluxDBWriteClient(client, writeOptions, clientToken);
+ } catch (RuntimeException | Error error) {
+ Arrays.fill(clientToken, '\0');
+ throw error;
+ }
+ }
+
+ private static final class OfficialInfluxDBWriteClient implements InfluxDBWriteClient {
+ private final InfluxDBClient client;
+ private final WriteOptions writeOptions;
+ private final char[] token;
+
+ private OfficialInfluxDBWriteClient(
+ InfluxDBClient client, WriteOptions writeOptions, char[] token) {
+ this.client = client;
+ this.writeOptions = writeOptions;
+ this.token = token;
+ }
+
+ @Override
+ public void writeRecords(List records) {
+ client.writeRecords(records, writeOptions);
+ }
+
+ @Override
+ public void close() throws Exception {
+ try {
+ client.close();
+ } finally {
+ Arrays.fill(token, '\0');
+ }
+ }
+ }
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/internal/FailureLogUtils.java b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/internal/FailureLogUtils.java
new file mode 100644
index 00000000..db4b4145
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/internal/FailureLogUtils.java
@@ -0,0 +1,58 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ */
+package software.amazon.timestream.influxdb3.flink.internal;
+
+/**
+ * Escapes values for single-line logs and limits their size.
+ *
+ * This utility does not redact secrets or other sensitive values.
+ */
+final class FailureLogUtils {
+ static final int MAX_LOGGED_CHARACTERS = 4_096;
+ private static final char[] HEX = "0123456789abcdef".toCharArray();
+
+ private FailureLogUtils() {}
+
+ static String escapeAndTruncateForLog(String value) {
+ if (value == null) {
+ return "";
+ }
+ StringBuilder escaped =
+ new StringBuilder(Math.min(value.length(), MAX_LOGGED_CHARACTERS));
+ int index = 0;
+ int lastEllipsisSafeIndex = 0;
+ int lastEllipsisSafeLength = 0;
+ while (index < value.length()) {
+ int codePoint = value.codePointAt(index);
+ if (requiresEscaping(codePoint)) {
+ escaped.append("\\u");
+ escaped.append(HEX[(codePoint >>> 12) & 0xf]);
+ escaped.append(HEX[(codePoint >>> 8) & 0xf]);
+ escaped.append(HEX[(codePoint >>> 4) & 0xf]);
+ escaped.append(HEX[codePoint & 0xf]);
+ } else {
+ escaped.appendCodePoint(codePoint);
+ }
+ index += Character.charCount(codePoint);
+ if (escaped.length() <= MAX_LOGGED_CHARACTERS - 3) {
+ lastEllipsisSafeIndex = index;
+ lastEllipsisSafeLength = escaped.length();
+ }
+ if (escaped.length() > MAX_LOGGED_CHARACTERS) {
+ escaped.setLength(lastEllipsisSafeLength);
+ index = lastEllipsisSafeIndex;
+ break;
+ }
+ }
+ if (index < value.length()) {
+ escaped.append("...");
+ }
+ return escaped.toString();
+ }
+
+ private static boolean requiresEscaping(int codePoint) {
+ return Character.isISOControl(codePoint) || codePoint == 0x2028 || codePoint == 0x2029;
+ }
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/internal/InfluxDB3SinkConfig.java b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/internal/InfluxDB3SinkConfig.java
new file mode 100644
index 00000000..9df31eb8
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/internal/InfluxDB3SinkConfig.java
@@ -0,0 +1,319 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ */
+package software.amazon.timestream.influxdb3.flink.internal;
+
+import org.apache.flink.annotation.Internal;
+
+import com.influxdb.v3.client.write.WritePrecision;
+import software.amazon.timestream.influxdb3.flink.InfluxDB3Sink;
+import software.amazon.timestream.influxdb3.flink.InfluxDB3SinkBuilder;
+import software.amazon.timestream.influxdb3.flink.auth.TokenProvider;
+import software.amazon.timestream.influxdb3.flink.failure.WriteFailureHandler;
+
+import java.io.Serializable;
+import java.net.URI;
+import java.time.Duration;
+
+/**
+ * Internal immutable runtime configuration for {@link InfluxDB3Sink}.
+ *
+ * Users configure the connector through {@link InfluxDB3SinkBuilder}.
+ */
+@Internal
+public final class InfluxDB3SinkConfig implements Serializable {
+ private static final long serialVersionUID = 1L;
+
+ private final URI endpoint;
+ private final String database;
+ private final TokenProvider tokenProvider;
+ private final WriteFailureHandler failureHandler;
+ private final WritePrecision writePrecision;
+ private final int maxBatchSize;
+ private final int maxInFlightRequests;
+ private final int maxBufferedRequests;
+ private final long maxBatchSizeInBytes;
+ private final long maxBufferedBytes;
+ private final long maxTimeInBufferMillis;
+ private final long maxRecordSizeInBytes;
+ private final Duration connectionTimeout;
+ private final Duration writeTimeout;
+ private final Duration requestTimeout;
+ private final boolean failOnRequestTimeout;
+ private final boolean gzipEnabled;
+ private final boolean acceptPartial;
+ private final boolean noSync;
+ private final boolean failOnValidation;
+ private final boolean failOnRetryExhaustion;
+ private final boolean printFailedRequests;
+ private final int maxRetries;
+ private final Duration initialRetryBackoff;
+ private final Duration maxRetryBackoff;
+ private final double retryJitter;
+ private final boolean managedFlinkMetricsEnabled;
+ private final String managedFlinkMetricsSinkName;
+
+ public InfluxDB3SinkConfig(
+ URI endpoint,
+ String database,
+ TokenProvider tokenProvider,
+ WriteFailureHandler failureHandler,
+ WritePrecision writePrecision,
+ int maxBatchSize,
+ int maxInFlightRequests,
+ int maxBufferedRequests,
+ long maxBatchSizeInBytes,
+ long maxBufferedBytes,
+ long maxTimeInBufferMillis,
+ long maxRecordSizeInBytes,
+ Duration connectionTimeout,
+ Duration writeTimeout,
+ Duration requestTimeout,
+ boolean failOnRequestTimeout,
+ boolean gzipEnabled,
+ boolean acceptPartial,
+ boolean noSync,
+ boolean failOnValidation,
+ boolean failOnRetryExhaustion,
+ boolean printFailedRequests,
+ int maxRetries,
+ Duration initialRetryBackoff,
+ Duration maxRetryBackoff,
+ double retryJitter,
+ boolean managedFlinkMetricsEnabled,
+ String managedFlinkMetricsSinkName) {
+ this.endpoint = endpoint;
+ this.database = database;
+ this.tokenProvider = tokenProvider;
+ this.failureHandler = failureHandler;
+ this.writePrecision = writePrecision;
+ this.maxBatchSize = maxBatchSize;
+ this.maxInFlightRequests = maxInFlightRequests;
+ this.maxBufferedRequests = maxBufferedRequests;
+ this.maxBatchSizeInBytes = maxBatchSizeInBytes;
+ this.maxBufferedBytes = maxBufferedBytes;
+ this.maxTimeInBufferMillis = maxTimeInBufferMillis;
+ this.maxRecordSizeInBytes = maxRecordSizeInBytes;
+ this.connectionTimeout = connectionTimeout;
+ this.writeTimeout = writeTimeout;
+ this.requestTimeout = requestTimeout;
+ this.failOnRequestTimeout = failOnRequestTimeout;
+ this.gzipEnabled = gzipEnabled;
+ this.acceptPartial = acceptPartial;
+ this.noSync = noSync;
+ this.failOnValidation = failOnValidation;
+ this.failOnRetryExhaustion = failOnRetryExhaustion;
+ this.printFailedRequests = printFailedRequests;
+ this.maxRetries = maxRetries;
+ this.initialRetryBackoff = initialRetryBackoff;
+ this.maxRetryBackoff = maxRetryBackoff;
+ this.retryJitter = retryJitter;
+ this.managedFlinkMetricsEnabled = managedFlinkMetricsEnabled;
+ this.managedFlinkMetricsSinkName = managedFlinkMetricsSinkName;
+ }
+
+ /** @return base HTTP or HTTPS cluster endpoint */
+ public URI getEndpoint() {
+ return endpoint;
+ }
+
+ /** @return target database name */
+ public String getDatabase() {
+ return database;
+ }
+
+ /** @return token provider initialized by each sink subtask */
+ public TokenProvider getTokenProvider() {
+ return tokenProvider;
+ }
+
+ /** @return configured record-level failure handler */
+ public WriteFailureHandler getFailureHandler() {
+ return failureHandler;
+ }
+
+ /** @return precision used to interpret line protocol timestamps */
+ public WritePrecision getWritePrecision() {
+ return writePrecision;
+ }
+
+ /** @return maximum number of records in one write request */
+ public int getMaxBatchSize() {
+ return maxBatchSize;
+ }
+
+ /** @return maximum number of concurrent write requests */
+ public int getMaxInFlightRequests() {
+ return maxInFlightRequests;
+ }
+
+ /** @return maximum number of records buffered by one sink subtask */
+ public int getMaxBufferedRequests() {
+ return maxBufferedRequests;
+ }
+
+ /** @return maximum uncompressed size of one write request */
+ public long getMaxBatchSizeInBytes() {
+ return maxBatchSizeInBytes;
+ }
+
+ /** @return maximum uncompressed payload bytes buffered by one sink subtask */
+ public long getMaxBufferedBytes() {
+ return maxBufferedBytes;
+ }
+
+ /** @return maximum buffering time before a request is sent */
+ public long getMaxTimeInBufferMillis() {
+ return maxTimeInBufferMillis;
+ }
+
+ /** @return maximum uncompressed size of one line protocol record */
+ public long getMaxRecordSizeInBytes() {
+ return maxRecordSizeInBytes;
+ }
+
+ /** @return timeout for establishing an InfluxDB HTTP connection */
+ public Duration getConnectionTimeout() {
+ return connectionTimeout;
+ }
+
+ /** @return hard deadline for one blocking InfluxDB HTTP write attempt */
+ public Duration getWriteTimeout() {
+ return writeTimeout;
+ }
+
+ /** @return timeout for Flink to receive a write result */
+ public Duration getRequestTimeout() {
+ return requestTimeout;
+ }
+
+ /** @return whether an expired request timeout fails the sink */
+ public boolean isFailOnRequestTimeout() {
+ return failOnRequestTimeout;
+ }
+
+ /** @return whether write payloads are gzip compressed */
+ public boolean isGzipEnabled() {
+ return gzipEnabled;
+ }
+
+ /** @return whether the server may accept valid rows from a partially invalid batch */
+ public boolean isAcceptPartial() {
+ return acceptPartial;
+ }
+
+ /** @return whether the server may acknowledge before synchronizing durable storage */
+ public boolean isNoSync() {
+ return noSync;
+ }
+
+ /** @return whether local and non-partial HTTP 400/422 validation failures fail the sink */
+ public boolean isFailOnValidation() {
+ return failOnValidation;
+ }
+
+ /** @return whether retry exhaustion fails the sink instead of dropping affected records */
+ public boolean isFailOnRetryExhaustion() {
+ return failOnRetryExhaustion;
+ }
+
+ /**
+ * @return whether terminally dropped or failed line protocol is written, without redaction,
+ * to the connector log
+ */
+ public boolean isPrintFailedRequests() {
+ return printFailedRequests;
+ }
+
+ /** @return maximum retries after the initial write attempt */
+ public int getMaxRetries() {
+ return maxRetries;
+ }
+
+ /** @return delay before the first retry */
+ public Duration getInitialRetryBackoff() {
+ return initialRetryBackoff;
+ }
+
+ /** @return maximum retry delay */
+ public Duration getMaxRetryBackoff() {
+ return maxRetryBackoff;
+ }
+
+ /** @return proportional jitter applied to retry delays */
+ public double getRetryJitter() {
+ return retryJitter;
+ }
+
+ /** @return whether metrics are also registered for Managed Flink CloudWatch publication */
+ public boolean isManagedFlinkMetricsEnabled() {
+ return managedFlinkMetricsEnabled;
+ }
+
+ /** @return {@code Sink} dimension for Managed Flink metrics, or {@code null} when unset */
+ public String getManagedFlinkMetricsSinkName() {
+ return managedFlinkMetricsSinkName;
+ }
+
+ @Override
+ public String toString() {
+ return "InfluxDB3SinkConfig{"
+ + "endpoint="
+ + endpoint
+ + ", database='"
+ + database
+ + '\''
+ + ", tokenProviderType="
+ + tokenProvider.getClass().getName()
+ + ", writePrecision="
+ + writePrecision
+ + ", maxBatchSize="
+ + maxBatchSize
+ + ", maxInFlightRequests="
+ + maxInFlightRequests
+ + ", maxBufferedRequests="
+ + maxBufferedRequests
+ + ", maxBatchSizeInBytes="
+ + maxBatchSizeInBytes
+ + ", maxBufferedBytes="
+ + maxBufferedBytes
+ + ", maxTimeInBufferMillis="
+ + maxTimeInBufferMillis
+ + ", maxRecordSizeInBytes="
+ + maxRecordSizeInBytes
+ + ", connectionTimeout="
+ + connectionTimeout
+ + ", writeTimeout="
+ + writeTimeout
+ + ", requestTimeout="
+ + requestTimeout
+ + ", failOnRequestTimeout="
+ + failOnRequestTimeout
+ + ", gzipEnabled="
+ + gzipEnabled
+ + ", acceptPartial="
+ + acceptPartial
+ + ", noSync="
+ + noSync
+ + ", failOnValidation="
+ + failOnValidation
+ + ", failOnRetryExhaustion="
+ + failOnRetryExhaustion
+ + ", printFailedRequests="
+ + printFailedRequests
+ + ", maxRetries="
+ + maxRetries
+ + ", initialRetryBackoff="
+ + initialRetryBackoff
+ + ", maxRetryBackoff="
+ + maxRetryBackoff
+ + ", retryJitter="
+ + retryJitter
+ + ", managedFlinkMetricsEnabled="
+ + managedFlinkMetricsEnabled
+ + ", managedFlinkMetricsSinkName="
+ + managedFlinkMetricsSinkName
+ + '}';
+ }
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/internal/InfluxDB3SinkWriter.java b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/internal/InfluxDB3SinkWriter.java
new file mode 100644
index 00000000..217941e0
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/internal/InfluxDB3SinkWriter.java
@@ -0,0 +1,262 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ */
+package software.amazon.timestream.influxdb3.flink.internal;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.api.connector.sink2.SinkWriter;
+import org.apache.flink.api.connector.sink2.WriterInitContext;
+import org.apache.flink.connector.base.sink.writer.AsyncSinkWriter;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+import org.apache.flink.connector.base.sink.writer.ResultHandler;
+import org.apache.flink.connector.base.sink.writer.config.AsyncSinkWriterConfiguration;
+import org.apache.flink.connector.base.sink.writer.strategy.AIMDScalingStrategy;
+import org.apache.flink.connector.base.sink.writer.strategy.CongestionControlRateLimitingStrategy;
+import org.apache.flink.connector.base.sink.writer.strategy.RateLimitingStrategy;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import software.amazon.timestream.influxdb3.flink.InfluxDB3SinkException;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.Collection;
+import java.util.List;
+import java.util.Objects;
+import java.util.stream.Collectors;
+
+/** Flink-facing writer that coordinates buffering, write execution, and failure handling. */
+@Internal
+public final class InfluxDB3SinkWriter
+ extends AsyncSinkWriter {
+ private static final Logger LOG = LoggerFactory.getLogger(InfluxDB3SinkWriter.class);
+
+ private final InfluxDB3SinkConfig config;
+ private final PayloadSizeTrackingRequestBuffer requestBuffer;
+ private final InfluxDBSinkMetrics metrics;
+ private final InfluxDBClientManager clientManager;
+ private final BlockingWriteExecutor writeExecutor;
+ private final InfluxDBFailureProcessor failureProcessor;
+
+ public InfluxDB3SinkWriter(
+ ElementConverter elementConverter,
+ WriterInitContext context,
+ InfluxDB3SinkConfig config,
+ InfluxDBClientFactory clientFactory,
+ Collection> recoveredState)
+ throws IOException {
+ this(
+ elementConverter,
+ context,
+ Objects.requireNonNull(config, "config"),
+ clientFactory,
+ recoveredState,
+ new PayloadSizeTrackingRequestBuffer<>());
+ }
+
+ private InfluxDB3SinkWriter(
+ ElementConverter elementConverter,
+ WriterInitContext context,
+ InfluxDB3SinkConfig config,
+ InfluxDBClientFactory clientFactory,
+ Collection> recoveredState,
+ PayloadSizeTrackingRequestBuffer requestBuffer)
+ throws IOException {
+ super(
+ elementConverter,
+ context,
+ writerConfiguration(config),
+ recoveredState,
+ new LineProtocolBatchCreator(config.getMaxBatchSizeInBytes()),
+ requestBuffer);
+ this.config = config;
+ this.requestBuffer = requestBuffer;
+ this.metrics =
+ new InfluxDBSinkMetrics(
+ context,
+ requestBuffer,
+ config.isManagedFlinkMetricsEnabled(),
+ config.getManagedFlinkMetricsSinkName());
+ this.clientManager =
+ new InfluxDBClientManager(
+ config,
+ clientFactory,
+ metrics,
+ getFatalExceptionCons()::accept);
+ this.writeExecutor = new BlockingWriteExecutor(config, clientManager, metrics);
+ this.failureProcessor =
+ new InfluxDBFailureProcessor(
+ config,
+ clientManager,
+ writeExecutor::scheduleRetry,
+ metrics,
+ LOG);
+
+ LOG.info(
+ "InfluxDB sink payload limits per subtask: maxBufferedBytes={}, "
+ + "maxInFlightRequests={}, maxBatchSizeInBytes={}, "
+ + "estimatedRawPayloadUpperBoundBytes={}",
+ config.getMaxBufferedBytes(),
+ config.getMaxInFlightRequests(),
+ config.getMaxBatchSizeInBytes(),
+ estimatedRawPayloadUpperBoundBytes(config));
+ try {
+ clientManager.initialize();
+ } catch (IOException error) {
+ writeExecutor.shutdownImmediately();
+ throw error;
+ }
+ }
+
+ @Override
+ public void write(InputT element, SinkWriter.Context context)
+ throws IOException, InterruptedException {
+ long flushThreshold =
+ config.getMaxBufferedBytes() - config.getMaxRecordSizeInBytes();
+ if (!requestBuffer.isEmpty() && requestBuffer.totalSizeInBytes() > flushThreshold) {
+ super.flush(true);
+ }
+ super.write(element, context);
+ }
+
+ @Override
+ protected void submitRequestEntries(
+ List requestEntries,
+ ResultHandler resultHandler) {
+ SingleCompletionResultHandler guardedResultHandler =
+ new SingleCompletionResultHandler<>(
+ resultHandler,
+ metrics::batchOutcome);
+ if (clientManager.isClosed()) {
+ guardedResultHandler.completeExceptionally(
+ new InfluxDB3SinkException(
+ "Cannot submit writes after the sink writer closed"));
+ return;
+ }
+
+ List writableRequests =
+ handleValidationFailures(requestEntries, guardedResultHandler);
+ if (writableRequests == null) {
+ return;
+ }
+ if (writableRequests.isEmpty()) {
+ guardedResultHandler.complete();
+ return;
+ }
+
+ List records =
+ writableRequests.stream()
+ .map(InfluxDB3WriteRequest::getLineProtocol)
+ .collect(Collectors.toUnmodifiableList());
+ writeExecutor.submit(
+ writableRequests,
+ records,
+ guardedResultHandler,
+ failureProcessor::handleWriteFailure);
+ }
+
+ @Override
+ protected long getSizeInBytes(InfluxDB3WriteRequest requestEntry) {
+ if (requestEntry.isValidationFailure()) {
+ return 0L;
+ }
+ return requestEntry.getLineProtocol().getBytes(StandardCharsets.UTF_8).length;
+ }
+
+ private List handleValidationFailures(
+ List requests,
+ SingleCompletionResultHandler resultHandler) {
+ List validationFailures =
+ requests.stream()
+ .filter(InfluxDB3WriteRequest::isValidationFailure)
+ .collect(Collectors.toList());
+ if (validationFailures.isEmpty()) {
+ return requests;
+ }
+
+ metrics.recordsSendErrors(validationFailures.size());
+ if (config.isFailOnValidation()) {
+ resultHandler.completeExceptionally(
+ new InfluxDB3SinkException(
+ "Line protocol validation failed: "
+ + validationFailures
+ .get(0)
+ .getValidationFailureMessage()));
+ return null;
+ }
+
+ metrics.recordsDropped(validationFailures.size());
+ resultHandler.markRecordsDropped();
+ return requests.stream()
+ .filter(request -> !request.isValidationFailure())
+ .collect(Collectors.toList());
+ }
+
+ @Override
+ public void close() {
+ if (!clientManager.beginClose()) {
+ return;
+ }
+
+ Exception failure = writeExecutor.close();
+ failure = clientManager.closeResources(failure);
+ super.close();
+ if (failure != null) {
+ throw new InfluxDB3SinkException(
+ "Unable to close the InfluxDB sink writer", failure);
+ }
+ }
+
+ private static long estimatedRawPayloadUpperBoundBytes(InfluxDB3SinkConfig config) {
+ try {
+ return Math.addExact(
+ config.getMaxBufferedBytes(),
+ Math.multiplyExact(
+ (long) config.getMaxInFlightRequests(),
+ config.getMaxBatchSizeInBytes()));
+ } catch (ArithmeticException ignored) {
+ return Long.MAX_VALUE;
+ }
+ }
+
+ static AsyncSinkWriterConfiguration writerConfiguration(InfluxDB3SinkConfig config) {
+ return AsyncSinkWriterConfiguration.builder()
+ .setMaxBatchSize(config.getMaxBatchSize())
+ .setMaxBatchSizeInBytes(config.getMaxBatchSizeInBytes())
+ .setMaxInFlightRequests(config.getMaxInFlightRequests())
+ .setMaxBufferedRequests(config.getMaxBufferedRequests())
+ .setMaxTimeInBufferMS(config.getMaxTimeInBufferMillis())
+ .setMaxRecordSizeInBytes(config.getMaxRecordSizeInBytes())
+ .setRequestTimeoutMS(config.getRequestTimeout().toMillis())
+ .setFailOnTimeout(config.isFailOnRequestTimeout())
+ .setRateLimitingStrategy(rateLimitingStrategy(config))
+ .build();
+ }
+
+ /**
+ * Allows {@code maxInFlightRequests} full batches in flight from the start.
+ *
+ * Flink's default strategy starts at one batch and adds ten records per successful
+ * request, so a writer needs thousands of requests to reach its configured concurrency. This
+ * strategy starts at the configured concurrency, halves it when a request has failed or
+ * retried records, such as on HTTP 429, and adds one batch per successful request.
+ */
+ static RateLimitingStrategy rateLimitingStrategy(InfluxDB3SinkConfig config) {
+ int maxInFlightMessages =
+ (int)
+ Math.min(
+ Integer.MAX_VALUE,
+ (long) config.getMaxBatchSize()
+ * config.getMaxInFlightRequests());
+ return CongestionControlRateLimitingStrategy.builder()
+ .setMaxInFlightRequests(config.getMaxInFlightRequests())
+ .setInitialMaxInFlightMessages(maxInFlightMessages)
+ .setScalingStrategy(
+ AIMDScalingStrategy.builder(maxInFlightMessages)
+ .setIncreaseRate(config.getMaxBatchSize())
+ .build())
+ .build();
+ }
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/internal/InfluxDB3WriteRequest.java b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/internal/InfluxDB3WriteRequest.java
new file mode 100644
index 00000000..c58a3242
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/internal/InfluxDB3WriteRequest.java
@@ -0,0 +1,102 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ */
+package software.amazon.timestream.influxdb3.flink.internal;
+
+import org.apache.flink.annotation.Internal;
+
+import java.io.Serializable;
+import java.util.Objects;
+
+/** Buffered request state for one line protocol row. */
+@Internal
+public final class InfluxDB3WriteRequest implements Serializable {
+ private static final long serialVersionUID = 1L;
+
+ private final String lineProtocol;
+ private final int retryAttempt;
+ private final int authenticationRefreshes;
+ private final String validationFailureMessage;
+
+ public InfluxDB3WriteRequest(
+ String lineProtocol, int retryAttempt, int authenticationRefreshes) {
+ this(lineProtocol, retryAttempt, authenticationRefreshes, null);
+ }
+
+ private InfluxDB3WriteRequest(
+ String lineProtocol,
+ int retryAttempt,
+ int authenticationRefreshes,
+ String validationFailureMessage) {
+ if (validationFailureMessage == null) {
+ this.lineProtocol = Objects.requireNonNull(lineProtocol, "lineProtocol");
+ if (lineProtocol.isBlank()
+ || lineProtocol.indexOf('\n') >= 0
+ || lineProtocol.indexOf('\r') >= 0) {
+ throw new IllegalArgumentException(
+ "lineProtocol must contain exactly one non-blank line");
+ }
+ } else {
+ this.lineProtocol = null;
+ }
+ if (retryAttempt < 0) {
+ throw new IllegalArgumentException("retryAttempt must not be negative");
+ }
+ if (authenticationRefreshes < 0) {
+ throw new IllegalArgumentException("authenticationRefreshes must not be negative");
+ }
+ this.retryAttempt = retryAttempt;
+ this.authenticationRefreshes = authenticationRefreshes;
+ this.validationFailureMessage = validationFailureMessage;
+ }
+
+ public static InfluxDB3WriteRequest initial(String lineProtocol) {
+ return new InfluxDB3WriteRequest(lineProtocol, 0, 0);
+ }
+
+ static InfluxDB3WriteRequest validationFailure(String message) {
+ return new InfluxDB3WriteRequest(
+ null, 0, 0, Objects.requireNonNull(message, "message"));
+ }
+
+ public String getLineProtocol() {
+ return lineProtocol;
+ }
+
+ public int getRetryAttempt() {
+ return retryAttempt;
+ }
+
+ public int getAuthenticationRefreshes() {
+ return authenticationRefreshes;
+ }
+
+ public boolean isValidationFailure() {
+ return validationFailureMessage != null;
+ }
+
+ public String getValidationFailureMessage() {
+ return validationFailureMessage;
+ }
+
+ public InfluxDB3WriteRequest nextRetry() {
+ requireWritable();
+ return new InfluxDB3WriteRequest(
+ lineProtocol, Math.addExact(retryAttempt, 1), authenticationRefreshes);
+ }
+
+ public InfluxDB3WriteRequest afterAuthenticationRefresh() {
+ requireWritable();
+ return new InfluxDB3WriteRequest(
+ lineProtocol,
+ retryAttempt,
+ Math.addExact(authenticationRefreshes, 1));
+ }
+
+ private void requireWritable() {
+ if (isValidationFailure()) {
+ throw new IllegalStateException("A validation failure cannot be written or retried");
+ }
+ }
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/internal/InfluxDB3WriterStateSerializer.java b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/internal/InfluxDB3WriterStateSerializer.java
new file mode 100644
index 00000000..e80f14b5
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/internal/InfluxDB3WriterStateSerializer.java
@@ -0,0 +1,185 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ */
+package software.amazon.timestream.influxdb3.flink.internal;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.AsyncSinkWriterStateSerializer;
+
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.EOFException;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+
+/** Versioned checkpoint serializer for buffered InfluxDB line protocol requests. */
+@Internal
+public final class InfluxDB3WriterStateSerializer
+ extends AsyncSinkWriterStateSerializer {
+ private static final int VERSION = 1;
+ private static final int WRITE_REQUEST = 0;
+ private static final int VALIDATION_FAILURE = 1;
+ // Validation messages are connector-generated; this also bounds allocations from corrupt state.
+ private static final int MAX_VALIDATION_FAILURE_MESSAGE_SIZE_BYTES = 1_024;
+
+ private final long maxRecordSizeInBytes;
+
+ /** Creates a serializer that rejects line-protocol state above the configured record limit. */
+ public InfluxDB3WriterStateSerializer(long maxRecordSizeInBytes) {
+ if (maxRecordSizeInBytes <= 0) {
+ throw new IllegalArgumentException("maxRecordSizeInBytes must be positive");
+ }
+ this.maxRecordSizeInBytes = maxRecordSizeInBytes;
+ }
+
+ @Override
+ protected void serializeRequestToStream(
+ InfluxDB3WriteRequest request, DataOutputStream out) throws IOException {
+ if (request.isValidationFailure()) {
+ out.writeByte(VALIDATION_FAILURE);
+ writeBoundedString(
+ request.getValidationFailureMessage(),
+ "validation failure message",
+ MAX_VALIDATION_FAILURE_MESSAGE_SIZE_BYTES,
+ out);
+ } else {
+ out.writeByte(WRITE_REQUEST);
+ writeBoundedString(
+ request.getLineProtocol(),
+ "line protocol",
+ maxRecordSizeInBytes,
+ out);
+ out.writeInt(request.getRetryAttempt());
+ out.writeInt(request.getAuthenticationRefreshes());
+ }
+ }
+
+ @Override
+ protected InfluxDB3WriteRequest deserializeRequestFromStream(
+ long requestSize, DataInputStream in) throws IOException {
+ try {
+ int requestType = in.readUnsignedByte();
+ if (requestType == VALIDATION_FAILURE) {
+ if (requestSize != 0) {
+ throw new IOException(
+ "Corrupt state: validation failure request size must be zero");
+ }
+ return InfluxDB3WriteRequest.validationFailure(
+ readBoundedString(
+ in,
+ "validation failure message",
+ MAX_VALIDATION_FAILURE_MESSAGE_SIZE_BYTES));
+ }
+ if (requestType == WRITE_REQUEST) {
+ return createWriteRequest(
+ readLineProtocol(in, requestSize), in.readInt(), in.readInt());
+ }
+ throw new IOException("Corrupt state: unknown request type " + requestType);
+ } catch (EOFException error) {
+ EOFException truncated = new EOFException("Corrupt state: truncated write request");
+ truncated.initCause(error);
+ throw truncated;
+ }
+ }
+
+ private static InfluxDB3WriteRequest createWriteRequest(
+ String lineProtocol, int retryAttempt, int authenticationRefreshes)
+ throws IOException {
+ if (retryAttempt < 0 || authenticationRefreshes < 0) {
+ throw new IOException("Corrupt state: negative retry metadata");
+ }
+ try {
+ return new InfluxDB3WriteRequest(
+ lineProtocol, retryAttempt, authenticationRefreshes);
+ } catch (IllegalArgumentException e) {
+ throw new IOException("Corrupt state: invalid write request", e);
+ }
+ }
+
+ private static void writeBoundedString(
+ String value, String fieldName, long maxLength, DataOutputStream out)
+ throws IOException {
+ byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
+ if (bytes.length > maxLength) {
+ throw new IOException(
+ fieldName + " exceeds the maximum encoded length of " + maxLength + " bytes");
+ }
+ out.writeInt(bytes.length);
+ out.write(bytes);
+ }
+
+ private String readLineProtocol(DataInputStream in, long requestSize) throws IOException {
+ int length = readLength(in, "line protocol");
+ if (requestSize < 0 || length != requestSize) {
+ throw new IOException(
+ "Corrupt state: line protocol length "
+ + length
+ + " does not match request size "
+ + requestSize);
+ }
+ if (length > maxRecordSizeInBytes) {
+ throw new IOException(
+ "Corrupt state: line protocol length exceeds "
+ + maxRecordSizeInBytes
+ + " bytes");
+ }
+ return readStringBytes(in, "line protocol", length);
+ }
+
+ private static String readBoundedString(
+ DataInputStream in, String fieldName, int maxLength) throws IOException {
+ int length = readLength(in, fieldName);
+ if (length > maxLength) {
+ throw new IOException(
+ "Corrupt state: "
+ + fieldName
+ + " length exceeds "
+ + maxLength
+ + " bytes");
+ }
+ return readStringBytes(in, fieldName, length);
+ }
+
+ private static int readLength(DataInputStream in, String fieldName) throws IOException {
+ int length = in.readInt();
+ if (length < 0) {
+ throw new IOException("Corrupt state: negative " + fieldName + " length");
+ }
+ return length;
+ }
+
+ private static String readStringBytes(
+ DataInputStream in, String fieldName, int length) throws IOException {
+ byte[] bytes = new byte[length];
+ try {
+ in.readFully(bytes);
+ } catch (EOFException error) {
+ EOFException truncated =
+ new EOFException("Corrupt state: truncated " + fieldName + " value");
+ truncated.initCause(error);
+ throw truncated;
+ }
+ return new String(bytes, StandardCharsets.UTF_8);
+ }
+
+ @Override
+ public BufferedRequestState deserialize(
+ int version, byte[] serialized) throws IOException {
+ if (version != VERSION) {
+ throw new IOException("Unsupported writer state version: " + version);
+ }
+ if (serialized.length >= Long.BYTES + Integer.BYTES
+ && ByteBuffer.wrap(serialized).getInt(Long.BYTES) < 0) {
+ throw new IOException("Corrupt state: negative request count");
+ }
+ return super.deserialize(version, serialized);
+ }
+
+ @Override
+ public int getVersion() {
+ return VERSION;
+ }
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/internal/InfluxDBClientFactory.java b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/internal/InfluxDBClientFactory.java
new file mode 100644
index 00000000..e9568a50
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/internal/InfluxDBClientFactory.java
@@ -0,0 +1,17 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ */
+package software.amazon.timestream.influxdb3.flink.internal;
+
+import org.apache.flink.annotation.Internal;
+
+import java.io.Serializable;
+
+/** Creates write clients inside sink subtasks. */
+@Internal
+@FunctionalInterface
+public interface InfluxDBClientFactory extends Serializable {
+
+ InfluxDBWriteClient create(InfluxDB3SinkConfig config, char[] token);
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/internal/InfluxDBClientManager.java b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/internal/InfluxDBClientManager.java
new file mode 100644
index 00000000..8f885f52
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/internal/InfluxDBClientManager.java
@@ -0,0 +1,268 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ */
+package software.amazon.timestream.influxdb3.flink.internal;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import software.amazon.timestream.influxdb3.flink.InfluxDB3SinkException;
+import software.amazon.timestream.influxdb3.flink.auth.TokenProvider;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Consumer;
+
+/** Owns token lifecycle and reference-counted InfluxDB client generations. */
+final class InfluxDBClientManager {
+ private static final Logger LOG = LoggerFactory.getLogger(InfluxDBClientManager.class);
+
+ private final InfluxDB3SinkConfig config;
+ private final InfluxDBClientFactory clientFactory;
+ private final TokenProvider tokenProvider;
+ private final InfluxDBSinkMetrics metrics;
+ private final Consumer asynchronousCloseFailureHandler;
+ private final AtomicReference activeClient = new AtomicReference<>();
+ private final Set clients = ConcurrentHashMap.newKeySet();
+ private final AtomicBoolean closed = new AtomicBoolean();
+
+ InfluxDBClientManager(
+ InfluxDB3SinkConfig config,
+ InfluxDBClientFactory clientFactory,
+ InfluxDBSinkMetrics metrics,
+ Consumer asynchronousCloseFailureHandler) {
+ this.config = Objects.requireNonNull(config, "config");
+ this.clientFactory = Objects.requireNonNull(clientFactory, "clientFactory");
+ this.tokenProvider = config.getTokenProvider();
+ this.metrics = Objects.requireNonNull(metrics, "metrics");
+ this.asynchronousCloseFailureHandler =
+ Objects.requireNonNull(
+ asynchronousCloseFailureHandler,
+ "asynchronousCloseFailureHandler");
+ }
+
+ void initialize() throws IOException {
+ try {
+ tokenProvider.open();
+ char[] token = null;
+ try {
+ token = requireToken(tokenProvider.getToken());
+ activateGeneration(0, token);
+ } finally {
+ clearToken(token);
+ }
+ } catch (Exception error) {
+ try {
+ tokenProvider.close();
+ } catch (IOException closeError) {
+ error.addSuppressed(closeError);
+ }
+ if (error instanceof IOException) {
+ throw (IOException) error;
+ }
+ throw new IOException("Unable to initialize the InfluxDB client", error);
+ }
+ }
+
+ boolean isClosed() {
+ return closed.get();
+ }
+
+ boolean beginClose() {
+ return closed.compareAndSet(false, true);
+ }
+
+ ClientLease acquire() {
+ while (!closed.get()) {
+ ClientGeneration generation = activeClient.get();
+ if (generation == null) {
+ throw new IllegalStateException("The InfluxDB client is not initialized");
+ }
+ ClientLease lease = generation.tryAcquire();
+ if (lease != null) {
+ return lease;
+ }
+ }
+ throw new IllegalStateException("The sink writer is closed");
+ }
+
+ synchronized boolean refresh(ClientGeneration failedClient) throws IOException {
+ if (closed.get()) {
+ throw new IOException("Cannot refresh the InfluxDB client after the writer closed");
+ }
+ if (activeClient.get() != failedClient) {
+ return false;
+ }
+
+ char[] token = null;
+ try {
+ token = requireToken(tokenProvider.refreshToken());
+ activateGeneration(failedClient.generation + 1, token);
+ Exception closeError = failedClient.retire();
+ if (closeError != null) {
+ reportClientCloseFailure(closeError);
+ }
+ return true;
+ } finally {
+ clearToken(token);
+ }
+ }
+
+ Exception closeResources(Exception failure) {
+ for (ClientGeneration client : List.copyOf(clients)) {
+ Exception closeError = client.forceClose();
+ if (closeError != null) {
+ failure = appendFailure(failure, closeError);
+ }
+ }
+ try {
+ tokenProvider.close();
+ } catch (Exception error) {
+ failure = appendFailure(failure, error);
+ }
+ return failure;
+ }
+
+ int clientCount() {
+ return clients.size();
+ }
+
+ private InfluxDBWriteClient createClient(char[] token) {
+ return Objects.requireNonNull(
+ clientFactory.create(config, token),
+ "InfluxDBClientFactory returned null");
+ }
+
+ private void activateGeneration(int generationNumber, char[] token) {
+ ClientGeneration generation =
+ new ClientGeneration(generationNumber, createClient(token));
+ clients.add(generation);
+ metrics.clientGenerationOpened();
+ activeClient.set(generation);
+ }
+
+ private void reportClientCloseFailure(Exception error) {
+ if (closed.get()) {
+ LOG.warn(
+ "Unable to close a retired InfluxDB client during shutdown; "
+ + "final cleanup will retry",
+ error);
+ return;
+ }
+ // Continuing can leak one transport generation per token rotation, so this remains a
+ // connector-owned fatal lifecycle failure while the writer is running.
+ asynchronousCloseFailureHandler.accept(
+ new InfluxDB3SinkException(
+ "Unable to close a retired InfluxDB client", error));
+ }
+
+ private static char[] requireToken(char[] token) throws IOException {
+ if (token == null || token.length == 0) {
+ throw new IOException("TokenProvider returned an empty InfluxDB token");
+ }
+ return token;
+ }
+
+ private static void clearToken(char[] token) {
+ if (token != null) {
+ Arrays.fill(token, '\0');
+ }
+ }
+
+ private static Exception appendFailure(Exception existing, Exception additional) {
+ if (existing == null) {
+ return additional;
+ }
+ existing.addSuppressed(additional);
+ return existing;
+ }
+
+ final class ClientLease {
+ private final ClientGeneration generation;
+
+ private ClientLease(ClientGeneration generation) {
+ this.generation = generation;
+ }
+
+ InfluxDBWriteClient client() {
+ return generation.client;
+ }
+
+ ClientGeneration generation() {
+ return generation;
+ }
+
+ void release() {
+ Exception closeError = generation.release();
+ if (closeError != null) {
+ reportClientCloseFailure(closeError);
+ }
+ }
+ }
+
+ final class ClientGeneration {
+ private final int generation;
+ private final InfluxDBWriteClient client;
+ private int references;
+ private boolean retired;
+ private boolean clientClosed;
+
+ private ClientGeneration(int generation, InfluxDBWriteClient client) {
+ this.generation = generation;
+ this.client = client;
+ }
+
+ private synchronized ClientLease tryAcquire() {
+ if (retired || clientClosed) {
+ return null;
+ }
+ references++;
+ return new ClientLease(this);
+ }
+
+ private synchronized Exception release() {
+ if (references <= 0) {
+ return new IllegalStateException(
+ "InfluxDB client generation reference count underflow");
+ }
+ references--;
+ return closeIfEligible();
+ }
+
+ private synchronized Exception retire() {
+ retired = true;
+ return closeIfEligible();
+ }
+
+ private synchronized Exception forceClose() {
+ retired = true;
+ return closeClient();
+ }
+
+ private Exception closeIfEligible() {
+ return retired && references == 0 ? closeClient() : null;
+ }
+
+ private Exception closeClient() {
+ if (clientClosed) {
+ return null;
+ }
+ try {
+ client.close();
+ clientClosed = true;
+ metrics.clientGenerationClosed();
+ clients.remove(this);
+ return null;
+ } catch (Exception error) {
+ return error;
+ }
+ }
+ }
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/internal/InfluxDBFailureProcessor.java b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/internal/InfluxDBFailureProcessor.java
new file mode 100644
index 00000000..23ac2948
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/internal/InfluxDBFailureProcessor.java
@@ -0,0 +1,445 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ */
+package software.amazon.timestream.influxdb3.flink.internal;
+
+import org.slf4j.Logger;
+
+import com.influxdb.v3.client.InfluxDBApiHttpException;
+import com.influxdb.v3.client.InfluxDBPartialWriteException;
+import com.influxdb.v3.client.InfluxDBPartialWriteException.LineError;
+import software.amazon.timestream.influxdb3.flink.InfluxDB3SinkException;
+import software.amazon.timestream.influxdb3.flink.failure.FailureAction;
+import software.amazon.timestream.influxdb3.flink.failure.WriteFailure;
+
+import java.time.Duration;
+import java.time.ZonedDateTime;
+import java.time.format.DateTimeFormatter;
+import java.time.format.DateTimeParseException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.stream.Collectors;
+
+/** Applies authentication, partial-write, retry, drop, and terminal failure policy. */
+final class InfluxDBFailureProcessor {
+ private static final String UNKNOWN_PARTIAL_WRITE_ERROR = "unknown partial-write error";
+
+ private final InfluxDB3SinkConfig config;
+ private final InfluxDBClientManager clientManager;
+ private final RetryScheduler retryScheduler;
+ private final InfluxDBSinkMetrics metrics;
+ private final Logger log;
+ private final Object failureHandlerLock = new Object();
+
+ InfluxDBFailureProcessor(
+ InfluxDB3SinkConfig config,
+ InfluxDBClientManager clientManager,
+ RetryScheduler retryScheduler,
+ InfluxDBSinkMetrics metrics,
+ Logger log) {
+ this.config = Objects.requireNonNull(config, "config");
+ this.clientManager = Objects.requireNonNull(clientManager, "clientManager");
+ this.retryScheduler = Objects.requireNonNull(retryScheduler, "retryScheduler");
+ this.metrics = Objects.requireNonNull(metrics, "metrics");
+ this.log = Objects.requireNonNull(log, "log");
+ }
+
+ void handleWriteFailure(
+ InfluxDBClientManager.ClientGeneration client,
+ List requests,
+ Exception error,
+ SingleCompletionResultHandler resultHandler) {
+ InfluxDBApiHttpException httpError = findHttpError(error);
+ Integer statusCode = httpError == null ? null : httpError.statusCode();
+ if (statusCode != null && (statusCode == 401 || statusCode == 403)) {
+ handleAuthenticationFailure(
+ client, requests, error, statusCode, resultHandler);
+ return;
+ }
+ if (statusCode != null && statusCode == 413) {
+ metrics.recordsSendErrors(requests.size());
+ logFailedRequests(requests, statusCode, "InfluxDB rejected an oversized batch");
+ resultHandler.completeExceptionally(
+ new InfluxDB3SinkException(
+ "InfluxDB rejected a write batch with HTTP 413", error));
+ return;
+ }
+ if (statusCode != null && statusCode == 429) {
+ metrics.throttledRequest();
+ }
+ if (config.isAcceptPartial() && error instanceof InfluxDBPartialWriteException) {
+ handlePartialWrite(
+ requests,
+ (InfluxDBPartialWriteException) error,
+ resultHandler);
+ return;
+ }
+ metrics.recordsSendErrors(requests.size());
+ applyFailureDecisions(
+ requests,
+ error,
+ httpError,
+ false,
+ Collections.emptyMap(),
+ resultHandler);
+ }
+
+ private void handleAuthenticationFailure(
+ InfluxDBClientManager.ClientGeneration failedClient,
+ List requests,
+ Exception error,
+ Integer statusCode,
+ SingleCompletionResultHandler resultHandler) {
+ metrics.recordsSendErrors(requests.size());
+ if (requests.stream().anyMatch(request -> request.getAuthenticationRefreshes() >= 1)) {
+ logFailedRequests(
+ requests, statusCode, "Authentication remained rejected after token refresh");
+ resultHandler.completeExceptionally(
+ new InfluxDB3SinkException(
+ "InfluxDB authentication failed after one token refresh", error));
+ return;
+ }
+
+ try {
+ if (clientManager.refresh(failedClient)) {
+ metrics.authenticationRefresh();
+ }
+ List retry =
+ requests.stream()
+ .map(InfluxDB3WriteRequest::afterAuthenticationRefresh)
+ .collect(Collectors.toList());
+ metrics.retries(retry.size());
+ resultHandler.retryForEntries(retry);
+ } catch (Exception refreshError) {
+ logFailedRequests(
+ requests,
+ null,
+ "Unable to refresh the InfluxDB authentication token");
+ resultHandler.completeExceptionally(
+ new InfluxDB3SinkException(
+ "Unable to refresh the InfluxDB authentication token",
+ refreshError));
+ }
+ }
+
+ private void handlePartialWrite(
+ List requests,
+ InfluxDBPartialWriteException error,
+ SingleCompletionResultHandler resultHandler) {
+ final Map failedLines;
+ try {
+ failedLines = mapPartialFailures(requests, error.lineErrors());
+ } catch (RuntimeException mappingError) {
+ metrics.recordsSendErrors(requests.size());
+ resultHandler.completeExceptionally(
+ mappingError instanceof InfluxDB3SinkException
+ ? (InfluxDB3SinkException) mappingError
+ : new InfluxDB3SinkException(
+ "Unable to process InfluxDB partial-write details",
+ mappingError));
+ return;
+ }
+
+ metrics.recordsWritten(requests.size() - failedLines.size());
+ metrics.bytesWritten(acceptedPayloadSizeInBytes(requests, failedLines));
+ metrics.recordsSendErrors(failedLines.size());
+ metrics.partialWriteFailures(failedLines.size());
+
+ List failedRequests = new ArrayList<>(failedLines.size());
+ Map messagesByFailedPosition = new LinkedHashMap<>();
+ int failedPosition = 0;
+ for (Map.Entry entry : failedLines.entrySet()) {
+ failedRequests.add(requests.get(entry.getKey()));
+ messagesByFailedPosition.put(failedPosition++, entry.getValue());
+ }
+ applyFailureDecisions(
+ failedRequests,
+ error,
+ error,
+ true,
+ messagesByFailedPosition,
+ resultHandler);
+ }
+
+ private void applyFailureDecisions(
+ List failedRequests,
+ Exception error,
+ InfluxDBApiHttpException httpError,
+ boolean partialWrite,
+ Map messages,
+ SingleCompletionResultHandler resultHandler) {
+ Integer statusCode = httpError == null ? null : httpError.statusCode();
+ List retry = new ArrayList<>();
+ int dropped = 0;
+
+ for (int index = 0; index < failedRequests.size(); index++) {
+ InfluxDB3WriteRequest request = failedRequests.get(index);
+ String serverMessage = messages.getOrDefault(index, error.getMessage());
+ final FailureAction action;
+ try {
+ if (!partialWrite && isValidationStatus(statusCode)) {
+ action =
+ config.isFailOnValidation()
+ ? FailureAction.FAIL
+ : FailureAction.DROP;
+ } else {
+ action =
+ classifyFailure(
+ new WriteFailure(
+ request.getLineProtocol(),
+ error,
+ request.getRetryAttempt(),
+ statusCode,
+ partialWrite,
+ serverMessage));
+ }
+ } catch (RuntimeException handlerError) {
+ logFailedRequest("FAIL", request, statusCode, serverMessage);
+ resultHandler.completeExceptionally(
+ new InfluxDB3SinkException(
+ "WriteFailureHandler failed while classifying an error",
+ handlerError));
+ return;
+ }
+
+ if (action == FailureAction.FAIL) {
+ logFailedRequest("FAIL", request, statusCode, serverMessage);
+ resultHandler.completeExceptionally(
+ new InfluxDB3SinkException(
+ "InfluxDB write failed with a non-retryable error", error));
+ return;
+ }
+ if (action == FailureAction.DROP) {
+ dropped++;
+ logFailedRequest("DROP", request, statusCode, serverMessage);
+ continue;
+ }
+ if (request.getRetryAttempt() >= config.getMaxRetries()) {
+ if (config.isFailOnRetryExhaustion()) {
+ logFailedRequest("FAIL", request, statusCode, serverMessage);
+ resultHandler.completeExceptionally(
+ new InfluxDB3SinkException(
+ "InfluxDB write exhausted "
+ + config.getMaxRetries()
+ + " retries",
+ error));
+ return;
+ }
+ dropped++;
+ logFailedRequest("DROP", request, statusCode, serverMessage);
+ continue;
+ }
+ retry.add(request.nextRetry());
+ }
+
+ if (dropped > 0) {
+ metrics.recordsDropped(dropped);
+ resultHandler.markRecordsDropped();
+ }
+ if (retry.isEmpty()) {
+ resultHandler.complete();
+ return;
+ }
+
+ int retryAttempt =
+ retry.stream()
+ .mapToInt(InfluxDB3WriteRequest::getRetryAttempt)
+ .max()
+ .orElse(1);
+ try {
+ Duration configuredDelay =
+ RetryDelayCalculator.calculate(
+ retryAttempt,
+ config.getInitialRetryBackoff(),
+ config.getMaxRetryBackoff(),
+ config.getRetryJitter());
+ Duration serverDelay = min(retryAfter(httpError), config.getMaxRetryBackoff());
+ Duration delay =
+ configuredDelay.compareTo(serverDelay) >= 0
+ ? configuredDelay
+ : serverDelay;
+ retryScheduler.schedule(retry, delay, resultHandler);
+ metrics.retries(retry.size());
+ metrics.retryScheduled(delay.toMillis(), retryAfter(httpError).toMillis());
+ } catch (RuntimeException retryError) {
+ resultHandler.completeExceptionally(
+ new InfluxDB3SinkException(
+ "Unable to schedule an InfluxDB write retry", retryError));
+ }
+ }
+
+ private FailureAction classifyFailure(WriteFailure failure) {
+ synchronized (failureHandlerLock) {
+ return Objects.requireNonNull(
+ config.getFailureHandler().onFailure(failure),
+ "WriteFailureHandler returned null");
+ }
+ }
+
+ private void logFailedRequest(
+ String action,
+ InfluxDB3WriteRequest request,
+ Integer statusCode,
+ String message) {
+ if (!config.isPrintFailedRequests()) {
+ return;
+ }
+ log.warn(
+ "InfluxDB request action={} status={} message={} lineProtocol={}",
+ action,
+ statusCode,
+ FailureLogUtils.escapeAndTruncateForLog(message),
+ FailureLogUtils.escapeAndTruncateForLog(request.getLineProtocol()));
+ }
+
+ private void logFailedRequests(
+ List requests,
+ Integer statusCode,
+ String message) {
+ requests.forEach(
+ request -> logFailedRequest("FAIL", request, statusCode, message));
+ }
+
+ private static boolean isValidationStatus(Integer statusCode) {
+ return statusCode != null && (statusCode == 400 || statusCode == 422);
+ }
+
+ private static Map mapPartialFailures(
+ List requests, List lineErrors) {
+ if (lineErrors.isEmpty()) {
+ throw new InfluxDB3SinkException(
+ "InfluxDB reported a partial write without line-level error details");
+ }
+
+ Map failures = new LinkedHashMap<>();
+ for (LineError lineError : lineErrors) {
+ Integer index = resolveLineIndex(requests, lineError, failures);
+ if (index == null) {
+ throw new InfluxDB3SinkException(
+ "Unable to map an InfluxDB partial-write error to its input line");
+ }
+ String message =
+ Objects.requireNonNullElse(
+ lineError.errorMessage(), UNKNOWN_PARTIAL_WRITE_ERROR);
+ failures.merge(
+ index,
+ message,
+ (first, second) -> first + "; " + second);
+ }
+ return failures;
+ }
+
+ private static Integer resolveLineIndex(
+ List requests,
+ LineError lineError,
+ Map alreadyMapped) {
+ Integer lineNumber = lineError.lineNumber();
+ String original = lineError.originalLine();
+ Integer lineNumberCandidate = null;
+ if (lineNumber != null) {
+ int candidate = lineNumber == 0 ? 0 : lineNumber - 1;
+ if (candidate >= 0 && candidate < requests.size()) {
+ lineNumberCandidate = candidate;
+ if (original == null) {
+ if (!alreadyMapped.containsKey(candidate)) {
+ return candidate;
+ }
+ } else if (original.equals(requests.get(candidate).getLineProtocol())) {
+ return candidate;
+ }
+ }
+ }
+
+ boolean originalMatchesMappedRequest = false;
+ if (original != null) {
+ for (int index = 0; index < requests.size(); index++) {
+ if (original.equals(requests.get(index).getLineProtocol())) {
+ if (!alreadyMapped.containsKey(index)) {
+ return index;
+ }
+ originalMatchesMappedRequest = true;
+ }
+ }
+ }
+ // InfluxDB can normalize original_line in partial-write responses, for
+ // example by removing quotes from string field values. Prefer an exact
+ // match when one exists, but otherwise trust a valid server line number.
+ return lineNumberCandidate != null
+ && !alreadyMapped.containsKey(lineNumberCandidate)
+ && !originalMatchesMappedRequest
+ ? lineNumberCandidate
+ : null;
+ }
+
+ private static Duration retryAfter(InfluxDBApiHttpException httpError) {
+ if (httpError == null || httpError.headers() == null) {
+ return Duration.ZERO;
+ }
+ return httpError.headers()
+ .firstValue("Retry-After")
+ .map(InfluxDBFailureProcessor::parseRetryAfter)
+ .orElse(Duration.ZERO);
+ }
+
+ private static long acceptedPayloadSizeInBytes(
+ List requests, Map failedLines) {
+ List accepted = new ArrayList<>(requests.size() - failedLines.size());
+ for (int index = 0; index < requests.size(); index++) {
+ if (!failedLines.containsKey(index)) {
+ accepted.add(requests.get(index).getLineProtocol());
+ }
+ }
+ return InfluxDBSinkMetrics.lineProtocolPayloadSizeInBytes(accepted);
+ }
+
+ static InfluxDBApiHttpException findHttpError(Throwable error) {
+ Throwable current = error;
+ while (current != null) {
+ if (current instanceof InfluxDBApiHttpException) {
+ return (InfluxDBApiHttpException) current;
+ }
+ Throwable cause = current.getCause();
+ if (cause == current) {
+ break;
+ }
+ current = cause;
+ }
+ return null;
+ }
+
+ private static Duration parseRetryAfter(String value) {
+ try {
+ long seconds = Long.parseLong(value);
+ return seconds <= 0 ? Duration.ZERO : Duration.ofSeconds(seconds);
+ } catch (NumberFormatException ignored) {
+ try {
+ Duration delay =
+ Duration.between(
+ ZonedDateTime.now(),
+ ZonedDateTime.parse(
+ value,
+ DateTimeFormatter.RFC_1123_DATE_TIME));
+ return delay.isNegative() ? Duration.ZERO : delay;
+ } catch (DateTimeParseException invalidDate) {
+ return Duration.ZERO;
+ }
+ }
+ }
+
+ private static Duration min(Duration first, Duration second) {
+ return first.compareTo(second) <= 0 ? first : second;
+ }
+
+ @FunctionalInterface
+ interface RetryScheduler {
+ void schedule(
+ List requests,
+ Duration delay,
+ SingleCompletionResultHandler resultHandler);
+ }
+}
diff --git a/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/internal/InfluxDBSinkMetrics.java b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/internal/InfluxDBSinkMetrics.java
new file mode 100644
index 00000000..bccd5700
--- /dev/null
+++ b/integrations/flink_connector/flink-connector-influxdb/src/main/java/software/amazon/timestream/influxdb3/flink/internal/InfluxDBSinkMetrics.java
@@ -0,0 +1,317 @@
+/*
+ * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ */
+package software.amazon.timestream.influxdb3.flink.internal;
+
+import org.apache.flink.api.common.operators.MailboxExecutor;
+import org.apache.flink.api.connector.sink2.WriterInitContext;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.Gauge;
+import org.apache.flink.metrics.Histogram;
+import org.apache.flink.metrics.MeterView;
+import org.apache.flink.metrics.MetricGroup;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+
+import com.influxdb.v3.client.InfluxDBApiHttpException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.util.List;
+import java.util.Objects;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
+
+/** Metric registration and mailbox-safe updates for one sink writer. */
+final class InfluxDBSinkMetrics {
+ private static final Logger LOG = LoggerFactory.getLogger(InfluxDBSinkMetrics.class);
+
+ /** Metric group that Managed Flink publishes to CloudWatch. */
+ static final String MANAGED_FLINK_METRIC_GROUP = "KinesisAnalytics";
+
+ static final String CONNECTOR_DIMENSION = "Connector";
+ static final String CONNECTOR_DIMENSION_VALUE = "TimestreamInfluxDB3";
+ static final String SINK_DIMENSION = "Sink";
+
+ /** Time window of the write latency percentiles published to Managed Flink. */
+ static final Duration MANAGED_FLINK_LATENCY_WINDOW = Duration.ofSeconds(60);
+
+ private static final int MANAGED_FLINK_LATENCY_CAPACITY = 4_096;
+
+ private final MailboxExecutor mailboxExecutor;
+ private final AtomicLong lastWriteLatencyMillis = new AtomicLong();
+ private final AtomicInteger lastBatchSizeLines = new AtomicInteger();
+ private final AtomicLong lastBatchSizeBytes = new AtomicLong();
+ private final AtomicInteger inFlightWriteRequests = new AtomicInteger();
+ private final AtomicInteger activeClientGenerations = new AtomicInteger();
+ private final AtomicLong maxRetryAfterMillis = new AtomicLong();
+
+ private final Counter numRecordsWritten;
+ private final Counter numRecordsSendErrors;
+ private final Counter numRecordsDropped;
+ private final Counter numRetries;
+ private final Counter numPartialWriteFailures;
+ private final Counter numAuthenticationRefreshes;
+ private final Counter numThrottledRequests;
+ private final Counter numWriteTimeouts;
+ private final Counter numBatchesSuccess;
+ private final Counter numBatchesCompletedWithDrops;
+ private final Counter numBatchesRetried;
+ private final Counter numBatchesFailed;
+ private final Counter numBytesWritten;
+ private final Counter numBytesOut;
+ private final Counter numRetryDelayMillis;
+ private final Counter numServerErrors;
+ private final Counter numClientErrors;
+ private final Counter numConnectionErrors;
+ private final Histogram writeLatencyMillis;
+ /** Recent write latencies for the published percentiles; {@code null} when not published. */
+ private final TimeWindowedQuantiles recentWriteLatencyMillis;
+
+ InfluxDBSinkMetrics(
+ WriterInitContext context,
+ PayloadSizeTrackingRequestBuffer requestBuffer,
+ boolean managedFlinkMetricsEnabled,
+ String managedFlinkMetricsSinkName) {
+ this.mailboxExecutor =
+ Objects.requireNonNull(
+ context.getMailboxExecutor(), "context mailbox executor");
+ SinkWriterMetricGroup metrics = context.metricGroup();
+ this.numRecordsWritten = metrics.counter("numRecordsWritten");
+ this.numRecordsSendErrors = metrics.getNumRecordsSendErrorsCounter();
+ this.numRecordsDropped = metrics.counter("numRecordsDropped");
+ this.numRetries = metrics.counter("numRetries");
+ this.numPartialWriteFailures = metrics.counter("numPartialWriteFailures");
+ this.numAuthenticationRefreshes = metrics.counter("numAuthenticationRefreshes");
+ this.numThrottledRequests = metrics.counter("numThrottledRequests");
+ this.numWriteTimeouts = metrics.counter("numWriteTimeouts");
+ this.numBatchesSuccess = metrics.counter("numBatchesSuccess");
+ this.numBatchesCompletedWithDrops =
+ metrics.counter("numBatchesCompletedWithDrops");
+ this.numBatchesRetried = metrics.counter("numBatchesRetried");
+ this.numBatchesFailed = metrics.counter("numBatchesFailed");
+ this.numBytesWritten = metrics.counter("numBytesWritten");
+ this.numBytesOut = metrics.getIOMetricGroup().getNumBytesOutCounter();
+ this.numRetryDelayMillis = metrics.counter("numRetryDelayMillis");
+ this.numServerErrors = metrics.counter("numServerErrors");
+ this.numClientErrors = metrics.counter("numClientErrors");
+ this.numConnectionErrors = metrics.counter("numConnectionErrors");
+ this.writeLatencyMillis =
+ metrics.histogram("writeLatencyMillis", new SlidingWindowHistogram(1_024));
+ metrics.gauge("lastWriteLatencyMillis", lastWriteLatencyMillis::get);
+ metrics.gauge("batchSizeLines", lastBatchSizeLines::get);
+ metrics.gauge("batchSizeBytes", lastBatchSizeBytes::get);
+ metrics.gauge("numBufferedBytes", requestBuffer::totalSizeInBytes);
+ metrics.gauge("numInFlightWriteRequests", inFlightWriteRequests::get);
+ metrics.gauge("numActiveClientGenerations", activeClientGenerations::get);
+ metrics.gauge("maxRetryAfterMillis", maxRetryAfterMillis::get);
+ this.recentWriteLatencyMillis =
+ managedFlinkMetricsEnabled
+ ? new TimeWindowedQuantiles(
+ MANAGED_FLINK_LATENCY_WINDOW, MANAGED_FLINK_LATENCY_CAPACITY)
+ : null;
+ if (managedFlinkMetricsEnabled) {
+ registerManagedFlinkMetrics(
+ managedFlinkMetricGroup(metrics, managedFlinkMetricsSinkName),
+ requestBuffer);
+ }
+ }
+
+ /**
+ * Registers the operational metrics a second time where Managed Flink publishes them.
+ *
+ * The same metric instances are registered, so both groups always report equal values.
+ * CloudWatch does not accept histograms, so write latency is published as percentile gauges
+ * over the writes of the last {@link #MANAGED_FLINK_LATENCY_WINDOW}. A fixed-count window
+ * would cover hours of history at low batch rates.
+ */
+ private void registerManagedFlinkMetrics(
+ MetricGroup group,
+ PayloadSizeTrackingRequestBuffer requestBuffer) {
+ group.counter("numRecordsWritten", numRecordsWritten);
+ group.counter("numRecordsSendErrors", numRecordsSendErrors);
+ group.counter("numRecordsDropped", numRecordsDropped);
+ group.counter("numRetries", numRetries);
+ group.counter("numPartialWriteFailures", numPartialWriteFailures);
+ group.counter("numAuthenticationRefreshes", numAuthenticationRefreshes);
+ group.counter("numThrottledRequests", numThrottledRequests);
+ group.counter("numWriteTimeouts", numWriteTimeouts);
+ group.counter("numBatchesFailed", numBatchesFailed);
+ group.counter("numBatchesSuccess", numBatchesSuccess);
+ group.counter("numBatchesRetried", numBatchesRetried);
+ group.counter("numBatchesCompletedWithDrops", numBatchesCompletedWithDrops);
+ group.counter("numBytesWritten", numBytesWritten);
+ group.counter("numBytesOut", numBytesOut);
+ group.counter("numRetryDelayMillis", numRetryDelayMillis);
+ group.counter("numServerErrors", numServerErrors);
+ group.counter("numClientErrors", numClientErrors);
+ group.counter("numConnectionErrors", numConnectionErrors);
+ group.meter("numRecordsWrittenPerSecond", new MeterView(numRecordsWritten));
+ group.meter("numBytesWrittenPerSecond", new MeterView(numBytesWritten));
+ group.meter("numRecordsDroppedPerSecond", new MeterView(numRecordsDropped));
+ group.meter("numRecordsSendErrorsPerSecond", new MeterView(numRecordsSendErrors));
+ group.meter("numBatchesFailedPerSecond", new MeterView(numBatchesFailed));
+ group.gauge("writeLatencyP50Millis", writeLatencyQuantile(0.50));
+ group.gauge("writeLatencyP95Millis", writeLatencyQuantile(0.95));
+ group.gauge("writeLatencyP99Millis", writeLatencyQuantile(0.99));
+ group.gauge("lastWriteLatencyMillis", lastWriteLatencyMillis::get);
+ group.gauge("batchSizeLines", lastBatchSizeLines::get);
+ group.gauge("batchSizeBytes", lastBatchSizeBytes::get);
+ group.gauge("numBufferedBytes", requestBuffer::totalSizeInBytes);
+ group.gauge("numInFlightWriteRequests", inFlightWriteRequests::get);
+ group.gauge("maxRetryAfterMillis", maxRetryAfterMillis::get);
+ }
+
+ private static MetricGroup managedFlinkMetricGroup(MetricGroup metrics, String sinkName) {
+ MetricGroup group =
+ metrics.addGroup(MANAGED_FLINK_METRIC_GROUP)
+ .addGroup(CONNECTOR_DIMENSION, CONNECTOR_DIMENSION_VALUE);
+ return sinkName == null ? group : group.addGroup(SINK_DIMENSION, sinkName);
+ }
+
+ private Gauge writeLatencyQuantile(double quantile) {
+ return () -> recentWriteLatencyMillis.getQuantile(quantile);
+ }
+
+ void recordsWritten(long count) {
+ increment(numRecordsWritten, count);
+ }
+
+ void bytesWritten(long bytes) {
+ increment(numBytesWritten, bytes);
+ }
+
+ void retryScheduled(long delayMillis, long retryAfterMillis) {
+ increment(numRetryDelayMillis, delayMillis);
+ maxRetryAfterMillis.accumulateAndGet(retryAfterMillis, Math::max);
+ }
+
+ /**
+ * Counts a write attempt that the InfluxDB client failed, by response class. HTTP 429 is
+ * counted separately as throttling; write-deadline timeouts never reach this method.
+ */
+ void writeAttemptFailed(Exception error) {
+ InfluxDBApiHttpException httpError = InfluxDBFailureProcessor.findHttpError(error);
+ if (httpError == null) {
+ increment(numConnectionErrors, 1L);
+ return;
+ }
+ int statusCode = httpError.statusCode();
+ if (statusCode >= 500) {
+ increment(numServerErrors, 1L);
+ } else if (statusCode >= 400 && statusCode != 429) {
+ increment(numClientErrors, 1L);
+ }
+ }
+
+ void recordsSendErrors(long count) {
+ increment(numRecordsSendErrors, count);
+ }
+
+ void recordsDropped(long count) {
+ increment(numRecordsDropped, count);
+ }
+
+ void retries(long count) {
+ increment(numRetries, count);
+ }
+
+ void partialWriteFailures(long count) {
+ increment(numPartialWriteFailures, count);
+ }
+
+ void authenticationRefresh() {
+ increment(numAuthenticationRefreshes, 1L);
+ }
+
+ void throttledRequest() {
+ increment(numThrottledRequests, 1L);
+ }
+
+ void writeTimeout() {
+ increment(numWriteTimeouts, 1L);
+ }
+
+ void writeRequestStarted() {
+ inFlightWriteRequests.incrementAndGet();
+ }
+
+ void writeRequestFinished() {
+ inFlightWriteRequests.decrementAndGet();
+ }
+
+ void clientGenerationOpened() {
+ activeClientGenerations.incrementAndGet();
+ }
+
+ void clientGenerationClosed() {
+ activeClientGenerations.decrementAndGet();
+ }
+
+ /** @return the batch's UTF-8 line protocol payload size in bytes */
+ long batchSubmitted(List records) {
+ long payloadSizeInBytes = lineProtocolPayloadSizeInBytes(records);
+ lastBatchSizeLines.set(records.size());
+ lastBatchSizeBytes.set(payloadSizeInBytes);
+ return payloadSizeInBytes;
+ }
+
+ void writeFinished(long startNanos) {
+ writeLatency(TimeUnit.NANOSECONDS.toMillis(Math.max(0L, System.nanoTime() - startNanos)));
+ }
+
+ void writeLatency(long latencyMillis) {
+ lastWriteLatencyMillis.set(latencyMillis);
+ writeLatencyMillis.update(latencyMillis);
+ if (recentWriteLatencyMillis != null) {
+ recentWriteLatencyMillis.update(latencyMillis);
+ }
+ }
+
+ void batchOutcome(SingleCompletionResultHandler.Outcome outcome) {
+ switch (outcome) {
+ case SUCCESS:
+ increment(numBatchesSuccess, 1L);
+ break;
+ case COMPLETED_WITH_DROPS:
+ increment(numBatchesCompletedWithDrops, 1L);
+ break;
+ case RETRIED:
+ increment(numBatchesRetried, 1L);
+ break;
+ case FAILED:
+ increment(numBatchesFailed, 1L);
+ break;
+ }
+ }
+
+ private void increment(Counter counter, long delta) {
+ if (delta == 0L) {
+ return;
+ }
+ try {
+ mailboxExecutor.execute(
+ () -> counter.inc(delta),
+ "Update InfluxDB sink metric");
+ } catch (RuntimeException error) {
+ LOG.debug("Unable to enqueue an InfluxDB sink metric update", error);
+ }
+ }
+
+ static long lineProtocolPayloadSizeInBytes(List