This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/dev/pr-13200-36bfa5c033e6c66f048e074d8e560ecae6617f8d in repository https://gitbox.apache.org/repos/asf/seatunnel.git
commit e58f114063a79c4d1e276b2b144a0364264958a8 Author: yidaimi <[email protected]> AuthorDate: Sun Nov 22 12:50:12 2026 +0000 [Fix][Connector-V2] Apply declared defaults of MongoDB sink buffer and retry options (#13200) Co-authored-by: yidaimi <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]> --- .../introduction/concepts/incompatible-changes.md | 8 + .../introduction/concepts/incompatible-changes.md | 8 + .../seatunnel/mongodb/sink/MongodbSinkFactory.java | 19 +- .../sink/MongodbSinkOptionDefaultsTest.java | 278 +++++++++++++++++++++ .../e2e/connector/v2/mongodb/MongodbIT.java | 48 ++++ ..._source_to_mongodb_explicit_buffer_options.conf | 56 +++++ ...e_source_to_mongodb_omitted_buffer_options.conf | 54 ++++ 7 files changed, 458 insertions(+), 13 deletions(-) diff --git a/docs/en/introduction/concepts/incompatible-changes.md b/docs/en/introduction/concepts/incompatible-changes.md index 874ad819626..6500f483c1e 100644 --- a/docs/en/introduction/concepts/incompatible-changes.md +++ b/docs/en/introduction/concepts/incompatible-changes.md @@ -5,6 +5,14 @@ You need to check this document before you upgrade to related version. ## dev +### MongoDB sink: omitted buffer and retry options now use their documented defaults + +- **Behavior change: a non-transactional MongoDB sink without `buffer-flush.*` or `retry.*` options writes in batches and retries failed writes** + - **Affected jobs**: MongoDB sinks with `transaction = false` (the default) that do not set one or more of `buffer-flush.max-rows`, `buffer-flush.interval`, `retry.max` and `retry.interval`. Sinks with `transaction = true` are not affected: they keep the rows until the next checkpoint and write them in one transaction through the committer, which uses neither the buffer options nor `retry.*`. + - **Description**: `MongodbSinkFactory` passed these options to the writer only when they were set explicitly. An omitted option was therefore `0` instead of its declared default, so every row was written with its own `bulkWrite` and a failed bulk write was not retried. The declared and documented defaults now apply: `buffer-flush.max-rows = 1000`, `buffer-flush.interval = 30000` ms, `retry.max = 3` and `retry.interval = 1000` ms. + - **Impact**: Rows are written in batches of up to 1000 rows instead of row by row, which makes writes to remote servers much faster. The first row of each writer is still written immediately. The 30-second interval is checked only when a new row arrives, so it does not limit how long a partial batch can wait when no more rows come in. A partial batch is written at the next checkpoint, when the writer closes, and at the engine timer flush if `sink.flush.interval` is set in `env` (Zeta [...] + - **Migration Guide**: No change is needed to get the documented behavior. To keep the previous behavior, set `buffer-flush.max-rows = 1` and `retry.max = 0` explicitly. A smaller `buffer-flush.max-rows` above 1 only reduces how many rows are buffered; it does not limit how long a partial batch waits when no more rows arrive. If a streaming job needs buffered rows to become visible within a bounded time, rely on checkpoints or set `sink.flush.interval` in `env` (Zeta). To write every r [...] + ### Http sink: `array_mode = true` sends each row as a JSON object - **Behavior change: the elements of the request body are JSON objects instead of strings** diff --git a/docs/zh/introduction/concepts/incompatible-changes.md b/docs/zh/introduction/concepts/incompatible-changes.md index 32933e6ffc5..a6fe59222dc 100644 --- a/docs/zh/introduction/concepts/incompatible-changes.md +++ b/docs/zh/introduction/concepts/incompatible-changes.md @@ -4,6 +4,14 @@ ## dev +### MongoDB Sink:未配置的缓冲与重试选项使用文档中的默认值 + +- **行为变更:未设置 `buffer-flush.*` 或 `retry.*` 选项的非事务 MongoDB Sink 会按批写入,并重试失败的写入** + - **影响范围**:`transaction = false`(默认值)且未设置 `buffer-flush.max-rows`、`buffer-flush.interval`、`retry.max`、`retry.interval` 中任意一个或多个选项的 MongoDB Sink。`transaction = true` 的 Sink 不受影响:它们会把数据保留到下一次 checkpoint,再由 committer 在一个事务中写入,既不使用缓冲选项,也不使用 `retry.*`。 + - **描述**:`MongodbSinkFactory` 此前只在显式设置时才把这些选项传给 writer,未设置的选项实际为 `0` 而不是声明的默认值,因此每一行都单独执行一次 `bulkWrite`,失败的批量写入也不会重试。现在会使用声明并写入文档的默认值:`buffer-flush.max-rows = 1000`、`buffer-flush.interval = 30000` 毫秒、`retry.max = 3`、`retry.interval = 1000` 毫秒。 + - **影响**:数据按批写入目标端,每批最多 1000 行,而不再逐行写入,写入远端服务器的吞吐量会大幅提升。每个 writer 的第一行仍会立即写入。30 秒间隔只在有新数据到达时检查,因此在没有后续数据时,它不能限制未写满的批次等待多久。未写满的批次会在下一次 checkpoint、writer 关闭时写入;如果在 `env` 中设置了 `sink.flush.interval`,引擎的定时 flush 也会写入(仅 Zeta 支持,默认关闭)。失败的批量写入会在作业失败前最多重试 3 次,依次等待 1、2、3 秒。重试会重新发送整个有序批次,因此在 `upsert-enable = false` 时,如果批次已部分写入,重试可能因主键重复而失败;这与此前显式设置 `retry.max` 时的行为相同。显式设置了这些选项的作业不受影响。 + - **迁移指南**:如需文档中描述的行为,无需修改配置。如需保持此前的行为,请显式设置 `buffer-flush.max-rows = 1` 和 `retry.max = 0`。把 `buffer-flush.max-rows` 调小到大于 1 的值只能减少缓冲的行数,在没有后续数据时,不能限制未写满的批次等待多久。如果流式作业需要缓冲的数据在一定时间内可见,请依赖 checkpoint,或在 `env` 中设置 `sink.flush.interval`(Zeta)。如需每一行立即写入,请设置 `buffer-flush.max-rows = 1`。(#13198) + ### Http Sink:`array_mode = true` 时每行作为 JSON 对象发送 - **行为变更:请求体数组的元素是 JSON 对象,而不再是字符串** diff --git a/seatunnel-connectors-v2/connector-mongodb/src/main/java/org/apache/seatunnel/connectors/seatunnel/mongodb/sink/MongodbSinkFactory.java b/seatunnel-connectors-v2/connector-mongodb/src/main/java/org/apache/seatunnel/connectors/seatunnel/mongodb/sink/MongodbSinkFactory.java index 467d8c08e8e..fe4867b5c96 100644 --- a/seatunnel-connectors-v2/connector-mongodb/src/main/java/org/apache/seatunnel/connectors/seatunnel/mongodb/sink/MongodbSinkFactory.java +++ b/seatunnel-connectors-v2/connector-mongodb/src/main/java/org/apache/seatunnel/connectors/seatunnel/mongodb/sink/MongodbSinkFactory.java @@ -76,13 +76,10 @@ public class MongodbSinkFactory implements TableSinkFactory, SupportSinkDryRunVa .withConnectString(connection) .withDatabase(database) .withCollection(collection); - if (readonlyConfig.getOptional(MongodbSinkOptions.BUFFER_FLUSH_MAX_ROWS).isPresent()) { - builder.withFlushSize(readonlyConfig.get(MongodbSinkOptions.BUFFER_FLUSH_MAX_ROWS)); - } - if (readonlyConfig.getOptional(MongodbSinkOptions.BUFFER_FLUSH_INTERVAL).isPresent()) { - builder.withBatchIntervalMs( - readonlyConfig.get(MongodbSinkOptions.BUFFER_FLUSH_INTERVAL)); - } + // Always read buffer and retry options: an omitted option must fall back to the default + // declared in MongodbSinkOptions, not to the builder's zero value. + builder.withFlushSize(readonlyConfig.get(MongodbSinkOptions.BUFFER_FLUSH_MAX_ROWS)); + builder.withBatchIntervalMs(readonlyConfig.get(MongodbSinkOptions.BUFFER_FLUSH_INTERVAL)); if (readonlyConfig.getOptional(MongodbSinkOptions.PRIMARY_KEY).isPresent()) { builder.withPrimaryKey( readonlyConfig.get(MongodbSinkOptions.PRIMARY_KEY).toArray(new String[0])); @@ -90,12 +87,8 @@ public class MongodbSinkFactory implements TableSinkFactory, SupportSinkDryRunVa if (readonlyConfig.getOptional(MongodbSinkOptions.UPSERT_ENABLE).isPresent()) { builder.withUpsertEnable(readonlyConfig.get(MongodbSinkOptions.UPSERT_ENABLE)); } - if (readonlyConfig.getOptional(MongodbSinkOptions.RETRY_MAX).isPresent()) { - builder.withRetryMax(readonlyConfig.get(MongodbSinkOptions.RETRY_MAX)); - } - if (readonlyConfig.getOptional(MongodbSinkOptions.RETRY_INTERVAL).isPresent()) { - builder.withRetryInterval(readonlyConfig.get(MongodbSinkOptions.RETRY_INTERVAL)); - } + builder.withRetryMax(readonlyConfig.get(MongodbSinkOptions.RETRY_MAX)); + builder.withRetryInterval(readonlyConfig.get(MongodbSinkOptions.RETRY_INTERVAL)); if (readonlyConfig.getOptional(MongodbSinkOptions.TRANSACTION).isPresent()) { builder.withTransaction(readonlyConfig.get(MongodbSinkOptions.TRANSACTION)); diff --git a/seatunnel-connectors-v2/connector-mongodb/src/test/java/org/apache/seatunnel/connectors/seatunnel/mongodb/sink/MongodbSinkOptionDefaultsTest.java b/seatunnel-connectors-v2/connector-mongodb/src/test/java/org/apache/seatunnel/connectors/seatunnel/mongodb/sink/MongodbSinkOptionDefaultsTest.java new file mode 100644 index 00000000000..e79dbb7da86 --- /dev/null +++ b/seatunnel-connectors-v2/connector-mongodb/src/test/java/org/apache/seatunnel/connectors/seatunnel/mongodb/sink/MongodbSinkOptionDefaultsTest.java @@ -0,0 +1,278 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.seatunnel.connectors.seatunnel.mongodb.sink; + +import org.apache.seatunnel.api.configuration.ReadonlyConfig; +import org.apache.seatunnel.api.sink.SinkWriter; +import org.apache.seatunnel.api.table.catalog.CatalogTableUtil; +import org.apache.seatunnel.api.table.factory.TableSinkFactoryContext; +import org.apache.seatunnel.api.table.type.BasicType; +import org.apache.seatunnel.api.table.type.SeaTunnelDataType; +import org.apache.seatunnel.api.table.type.SeaTunnelRow; +import org.apache.seatunnel.api.table.type.SeaTunnelRowType; +import org.apache.seatunnel.connectors.seatunnel.mongodb.config.MongodbSinkOptions; +import org.apache.seatunnel.connectors.seatunnel.mongodb.exception.MongodbConnectorException; +import org.apache.seatunnel.connectors.seatunnel.mongodb.internal.MongodbSingleCollectionProvider; + +import org.bson.BsonDocument; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.MockedConstruction; +import org.mockito.Mockito; + +import com.mongodb.MongoException; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.model.BulkWriteOptions; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Regression tests for the declared defaults of the MongoDB sink buffer and retry options. + * + * <p>The sink is created through {@link MongodbSinkFactory} exactly as the engine does, and the + * effective option values are observed through the writer behavior (number of bulk writes, retry + * attempts and back-off) against a mocked collection. + * + * <p>The writer compares {@code System.currentTimeMillis()} with the time of its last bulk write. + * To keep the tests independent of scheduling pauses, they set that time explicitly: far in the + * future to isolate the size threshold, or a fixed distance in the past to test the interval. + */ +class MongodbSinkOptionDefaultsTest { + + private static final SeaTunnelRowType ROW_TYPE = + new SeaTunnelRowType( + new String[] {"id"}, new SeaTunnelDataType<?>[] {BasicType.LONG_TYPE}); + + /** A last-write time in the future: the interval threshold can never be reached. */ + private static final long INTERVAL_NEVER_REACHED = Long.MAX_VALUE / 2; + + @Test + void omittedMaxRowsUsesDeclaredDefault() throws Exception { + // Default buffer-flush.max-rows = 1000. + Assertions.assertEquals(0, sizeTriggeredBulkWrites(baseConfig(), 999)); + Assertions.assertEquals(1, sizeTriggeredBulkWrites(baseConfig(), 1000)); + Assertions.assertEquals(2, sizeTriggeredBulkWrites(baseConfig(), 2000)); + } + + @Test + void explicitMaxRowsIsStillApplied() throws Exception { + Map<String, Object> config = baseConfig(); + config.put(MongodbSinkOptions.BUFFER_FLUSH_MAX_ROWS.key(), 10); + config.put(MongodbSinkOptions.BUFFER_FLUSH_INTERVAL.key(), 60_000L); + Assertions.assertEquals(100, sizeTriggeredBulkWrites(config, 1000)); + } + + @Test + void omittedIntervalUsesDeclaredDefault() throws Exception { + // Default buffer-flush.interval = 30000 ms, checked when a row is written. + Assertions.assertFalse(rowFlushesAfterIdleMs(baseConfig(), 25_000)); + Assertions.assertTrue(rowFlushesAfterIdleMs(baseConfig(), 30_000)); + } + + @Test + void explicitIntervalIsStillApplied() throws Exception { + Map<String, Object> config = baseConfig(); + config.put(MongodbSinkOptions.BUFFER_FLUSH_INTERVAL.key(), 60_000L); + Assertions.assertFalse(rowFlushesAfterIdleMs(config, 30_000)); + Assertions.assertTrue(rowFlushesAfterIdleMs(config, 60_000)); + + config.put(MongodbSinkOptions.BUFFER_FLUSH_INTERVAL.key(), -1L); + Assertions.assertFalse(rowFlushesAfterIdleMs(config, 3_600_000)); + } + + @Test + void omittedRetryMaxUsesDeclaredDefault() throws Exception { + Map<String, Object> config = baseConfig(); + config.put(MongodbSinkOptions.RETRY_INTERVAL.key(), 1L); + // Default retry.max = 3: one attempt plus three retries. + Assertions.assertEquals(4, attemptTimesUntilFailure(config).size()); + } + + @Test + void explicitRetryMaxIsStillApplied() throws Exception { + Map<String, Object> config = baseConfig(); + config.put(MongodbSinkOptions.RETRY_MAX.key(), 1); + config.put(MongodbSinkOptions.RETRY_INTERVAL.key(), 1L); + Assertions.assertEquals(2, attemptTimesUntilFailure(config).size()); + } + + @Test + void omittedRetryIntervalUsesDeclaredDefault() throws Exception { + Map<String, Object> config = baseConfig(); + config.put(MongodbSinkOptions.RETRY_MAX.key(), 1); + List<Long> attempts = attemptTimesUntilFailure(config); + Assertions.assertEquals(2, attempts.size()); + // Default retry.interval = 1000 ms before the first retry. + assertBackOffAtLeast(attempts, 0, 1000); + } + + @Test + void explicitRetryIntervalIsStillApplied() throws Exception { + Map<String, Object> config = baseConfig(); + config.put(MongodbSinkOptions.RETRY_MAX.key(), 2); + config.put(MongodbSinkOptions.RETRY_INTERVAL.key(), 50L); + List<Long> attempts = attemptTimesUntilFailure(config); + Assertions.assertEquals(3, attempts.size()); + // Linear back-off: retry.interval * attempt number. + assertBackOffAtLeast(attempts, 0, 50); + assertBackOffAtLeast(attempts, 1, 100); + } + + private static Map<String, Object> baseConfig() { + Map<String, Object> config = new HashMap<>(); + config.put(MongodbSinkOptions.URI.key(), "mongodb://localhost:27017"); + config.put(MongodbSinkOptions.DATABASE.key(), "test_database"); + config.put(MongodbSinkOptions.COLLECTION.key(), "test_collection"); + return config; + } + + private static MongodbSink createSink(Map<String, Object> config) { + TableSinkFactoryContext context = + new TableSinkFactoryContext( + CatalogTableUtil.getCatalogTable("test_table", ROW_TYPE), + ReadonlyConfig.fromMap(config), + MongodbSinkOptionDefaultsTest.class.getClassLoader()); + return (MongodbSink) new MongodbSinkFactory().createSink(context).createSink(); + } + + private static SeaTunnelRow row(long id) { + return new SeaTunnelRow(new Object[] {id}); + } + + /** Writes {@code rows} rows with the interval threshold disabled and counts bulk writes. */ + private static int sizeTriggeredBulkWrites(Map<String, Object> config, int rows) + throws Exception { + AtomicInteger bulkWrites = new AtomicInteger(); + try (MockedConstruction<MongodbSingleCollectionProvider> ignored = + mockCollectionProvider(countingCollection(bulkWrites))) { + MongodbWriter writer = createSink(config).createWriter(mock(SinkWriter.Context.class)); + try { + setLastSendTime(writer, INTERVAL_NEVER_REACHED); + for (int i = 0; i < rows; i++) { + writer.write(row(i)); + } + return bulkWrites.get(); + } finally { + closeQuietly(writer); + } + } + } + + /** Returns whether one row is flushed when the last bulk write was {@code idleMs} ago. */ + private static boolean rowFlushesAfterIdleMs(Map<String, Object> config, long idleMs) + throws Exception { + // Keep the size threshold out of the way. + config.put(MongodbSinkOptions.BUFFER_FLUSH_MAX_ROWS.key(), 1_000_000); + AtomicInteger bulkWrites = new AtomicInteger(); + try (MockedConstruction<MongodbSingleCollectionProvider> ignored = + mockCollectionProvider(countingCollection(bulkWrites))) { + MongodbWriter writer = createSink(config).createWriter(mock(SinkWriter.Context.class)); + try { + setLastSendTime(writer, System.currentTimeMillis() - idleMs); + writer.write(row(1)); + return bulkWrites.get() == 1; + } finally { + closeQuietly(writer); + } + } + } + + /** Lets every bulk write fail and returns the time of each attempt in nanoseconds. */ + @SuppressWarnings("unchecked") + private static List<Long> attemptTimesUntilFailure(Map<String, Object> config) + throws Exception { + List<Long> attempts = Collections.synchronizedList(new ArrayList<>()); + MongoCollection<BsonDocument> collection = mock(MongoCollection.class); + doAnswer( + invocation -> { + attempts.add(System.nanoTime()); + throw new MongoException("simulated failure"); + }) + .when(collection) + .bulkWrite(anyList(), any(BulkWriteOptions.class)); + try (MockedConstruction<MongodbSingleCollectionProvider> ignored = + mockCollectionProvider(collection)) { + MongodbWriter writer = createSink(config).createWriter(mock(SinkWriter.Context.class)); + Assertions.assertThrows(MongodbConnectorException.class, () -> writer.write(row(1))); + List<Long> result = new ArrayList<>(attempts); + closeQuietly(writer); + return result; + } + } + + private static void assertBackOffAtLeast(List<Long> attempts, int retry, long minMs) { + long gapMs = (attempts.get(retry + 1) - attempts.get(retry)) / 1_000_000; + Assertions.assertTrue( + gapMs >= minMs, + "expected a back-off of at least " + + minMs + + " ms before retry " + + (retry + 1) + + ", got " + + gapMs + + " ms"); + } + + @SuppressWarnings("unchecked") + private static MongoCollection<BsonDocument> countingCollection(AtomicInteger bulkWrites) { + MongoCollection<BsonDocument> collection = mock(MongoCollection.class); + doAnswer( + invocation -> { + bulkWrites.incrementAndGet(); + return null; + }) + .when(collection) + .bulkWrite(anyList(), any(BulkWriteOptions.class)); + return collection; + } + + private static void setLastSendTime(MongodbWriter writer, long millis) throws Exception { + Field field = MongodbWriter.class.getDeclaredField("lastSendTime"); + field.setAccessible(true); + field.setLong(writer, millis); + } + + /** Closes the writer after the counts were taken; a flush failure on close is not relevant. */ + private static void closeQuietly(MongodbWriter writer) { + try { + writer.close(); + } catch (Exception ignored) { + // the remaining buffered rows are flushed on close; failures were already asserted + } + } + + private static MockedConstruction<MongodbSingleCollectionProvider> mockCollectionProvider( + MongoCollection<BsonDocument> collection) { + return Mockito.mockConstruction( + MongodbSingleCollectionProvider.class, + (provider, context) -> + when(provider.getDefaultCollection()).thenReturn(collection)); + } +} diff --git a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-mongodb-e2e/src/test/java/org/apache/seatunnel/e2e/connector/v2/mongodb/MongodbIT.java b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-mongodb-e2e/src/test/java/org/apache/seatunnel/e2e/connector/v2/mongodb/MongodbIT.java index 58d4368803a..60d010fc207 100644 --- a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-mongodb-e2e/src/test/java/org/apache/seatunnel/e2e/connector/v2/mongodb/MongodbIT.java +++ b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-mongodb-e2e/src/test/java/org/apache/seatunnel/e2e/connector/v2/mongodb/MongodbIT.java @@ -343,6 +343,54 @@ public class MongodbIT extends AbstractMongodbIT { clearData(MONGODB_SINK_TABLE); } + @TestTemplate + public void testSinkWithOmittedBufferAndRetryOptions(TestContainer container) + throws IOException, InterruptedException { + // Without buffer-flush.* / retry.*, the declared defaults apply: rows are batched + // (first row, then 1000, then a 233-row tail) and the tail below the batch size is + // still written before the job completes. + // The insert-command counter is server-wide; the tests of this class run sequentially. + try { + long insertsBefore = insertCommandCount(); + Container.ExecResult result = + container.executeJob("/fake_source_to_mongodb_omitted_buffer_options.conf"); + Assertions.assertEquals(0, result.getExitCode(), result.getStderr()); + long batchedInserts = insertCommandCount() - insertsBefore; + log.info("Omitted buffer options: {} insert commands for 1234 rows", batchedInserts); + + Assertions.assertEquals(1234, countDocuments("test_omitted_buffer_options")); + // One insert command per bulk write. Per-row writing, the previous behavior, would + // issue 1234; the bound leaves room for engine-specific extra flushes. + Assertions.assertTrue( + batchedInserts > 0 && batchedInserts <= 10, + "expected batched bulk writes, got " + batchedInserts + " insert commands"); + + // Control: explicit options keep their values (one bulk write per row). + insertsBefore = insertCommandCount(); + result = container.executeJob("/fake_source_to_mongodb_explicit_buffer_options.conf"); + Assertions.assertEquals(0, result.getExitCode(), result.getStderr()); + Assertions.assertEquals(1234, countDocuments("test_explicit_buffer_options")); + Assertions.assertEquals(1234, insertCommandCount() - insertsBefore); + } finally { + clearData("test_omitted_buffer_options"); + clearData("test_explicit_buffer_options"); + } + } + + private long countDocuments(String collection) { + return client.getDatabase(MONGODB_DATABASE).getCollection(collection).countDocuments(); + } + + /** Number of insert commands the server has executed; each bulk write is one command. */ + private long insertCommandCount() { + Document status = client.getDatabase("admin").runCommand(new Document("serverStatus", 1)); + Document insert = + status.get("metrics", Document.class) + .get("commands", Document.class) + .get("insert", Document.class); + return ((Number) insert.get("total")).longValue(); + } + @TestTemplate @DisabledOnContainer( value = {}, diff --git a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-mongodb-e2e/src/test/resources/fake_source_to_mongodb_explicit_buffer_options.conf b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-mongodb-e2e/src/test/resources/fake_source_to_mongodb_explicit_buffer_options.conf new file mode 100644 index 00000000000..ea7b3dfa40d --- /dev/null +++ b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-mongodb-e2e/src/test/resources/fake_source_to_mongodb_explicit_buffer_options.conf @@ -0,0 +1,56 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# Control for fake_source_to_mongodb_omitted_buffer_options.conf: the same 1234 rows with the +# previous effective behavior set explicitly (one bulk write per row, no retries). + +env { + parallelism = 1 + job.mode = "BATCH" + #spark config + spark.app.name = "SeaTunnel" + spark.executor.instances = 1 + spark.executor.cores = 1 + spark.executor.memory = "1g" + spark.master = local +} + +source { + FakeSource { + row.num = 1234 + split.num = 1 + plugin_output = "fake" + schema = { + fields { + id = bigint + name = string + } + } + } +} + +sink { + MongoDB { + plugin_input = "fake" + uri = "mongodb://e2e_mongodb:27017/test_db" + database = "test_db" + collection = "test_explicit_buffer_options" + buffer-flush.max-rows = 1 + buffer-flush.interval = -1 + retry.max = 0 + } +} diff --git a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-mongodb-e2e/src/test/resources/fake_source_to_mongodb_omitted_buffer_options.conf b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-mongodb-e2e/src/test/resources/fake_source_to_mongodb_omitted_buffer_options.conf new file mode 100644 index 00000000000..71868af84e9 --- /dev/null +++ b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-mongodb-e2e/src/test/resources/fake_source_to_mongodb_omitted_buffer_options.conf @@ -0,0 +1,54 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# Writes 1234 rows without buffer-flush.* and retry.* options, so the declared defaults apply +# (buffer-flush.max-rows = 1000). The first row is written at once, the next 1000 as one batch, +# and the last 233 rows stay below the batch size and must be written when the job finishes. + +env { + parallelism = 1 + job.mode = "BATCH" + #spark config + spark.app.name = "SeaTunnel" + spark.executor.instances = 1 + spark.executor.cores = 1 + spark.executor.memory = "1g" + spark.master = local +} + +source { + FakeSource { + row.num = 1234 + split.num = 1 + plugin_output = "fake" + schema = { + fields { + id = bigint + name = string + } + } + } +} + +sink { + MongoDB { + plugin_input = "fake" + uri = "mongodb://e2e_mongodb:27017/test_db" + database = "test_db" + collection = "test_omitted_buffer_options" + } +}
