You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@inlong.apache.org by "XiaoYou201 (via GitHub)" <gi...@apache.org> on 2024/05/16 04:52:00 UTC

[PR] [INLONG-10195][Sort] Hudi connector support audit ID. [inlong]

XiaoYou201 opened a new pull request, #10231:
URL: https://github.com/apache/inlong/pull/10231

   ### Prepare a Pull Request
   
    - [INLONG-10195][Sort] Hudi connector support audit ID
   
   - Fixes #10195 
   
   - Parent issue: https://github.com/apache/inlong/issues/8803
   
   ### Motivation
   
   Hudi connector not support audit function. So this pr will make it support audit function.
   
   ### Modifications
   
   Modify MongoDB connector sink.when sinkreceive data, it will send audit information at same time.Some implement are as follows:
   
   Program will get the audit information from the incoming sql statement and pass it to the StreamWriteFunction class. During StreamWrite , the program will report the number of data received.
   ![image](https://github.com/apache/inlong/assets/58425449/687395cc-c7d3-45c4-8d00-199910e00130)
   
   


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

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

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


Re: [PR] [INLONG-10195][Sort] Hudi connector support audit ID [inlong]

Posted by "XiaoYou201 (via GitHub)" <gi...@apache.org>.
XiaoYou201 commented on code in PR #10231:
URL: https://github.com/apache/inlong/pull/10231#discussion_r1607708038


##########
inlong-sort/sort-flink/sort-flink-v1.15/sort-connectors/hudi/src/main/java/org/apache/inlong/sort/hudi/sink/bucket/BucketStreamWriteFunction.java:
##########
@@ -0,0 +1,185 @@
+/*
+ * 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.inlong.sort.hudi.sink.bucket;
+
+import org.apache.inlong.sort.base.metric.MetricOption;
+import org.apache.inlong.sort.base.metric.SinkMetricData;
+
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.runtime.state.FunctionInitializationContext;
+import org.apache.flink.streaming.api.functions.ProcessFunction;
+import org.apache.flink.util.Collector;
+import org.apache.hudi.common.model.HoodieKey;
+import org.apache.hudi.common.model.HoodieRecord;
+import org.apache.hudi.common.model.HoodieRecordLocation;
+import org.apache.hudi.configuration.FlinkOptions;
+import org.apache.hudi.index.bucket.BucketIdentifier;
+import org.apache.hudi.sink.StreamWriteFunction;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * A stream write function with bucket hash index.
+ *
+ * <p>The task holds a fresh new local index: {(partition + bucket number) &rarr fileId} mapping, this index
+ * is used for deciding whether the incoming records in an UPDATE or INSERT.
+ * The index is local because different partition paths have separate items in the index.
+ *
+ * @param <I> the input type
+ */
+public class BucketStreamWriteFunction<I> extends StreamWriteFunction<I> {
+
+    private static final Logger LOG = LoggerFactory.getLogger(BucketStreamWriteFunction.class);
+
+    private int parallelism;
+
+    private int bucketNum;
+
+    private String indexKeyFields;
+
+    /**
+     * BucketID to file group mapping in each partition.
+     * Map(partition -> Map(bucketId, fileID)).
+     */
+    private Map<String, Map<Integer, String>> bucketIndex;
+
+    /**
+     * Incremental bucket index of the current checkpoint interval,
+     * it is needed because the bucket type('I' or 'U') should be decided based on the committed files view,
+     * all the records in one bucket should have the same bucket type.
+     */
+    private Set<String> incBucketIndex;
+    private final MetricOption metricOption;
+    private SinkMetricData sinkMetricData;
+
+    /**
+     * Constructs a BucketStreamWriteFunction.
+     *
+     * @param config The config options
+     */
+    public BucketStreamWriteFunction(Configuration config, MetricOption metricOption) {
+        super(config);
+        this.metricOption = metricOption;
+    }
+
+    @Override
+    public void open(Configuration parameters) throws IOException {

Review Comment:
   fixt it~ thx~



##########
inlong-sort/sort-flink/sort-flink-v1.15/sort-connectors/hudi/src/main/java/org/apache/inlong/sort/hudi/sink/StreamWriteFunction.java:
##########
@@ -0,0 +1,496 @@
+/*
+ * 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.inlong.sort.hudi.sink;
+
+import org.apache.inlong.sort.base.metric.MetricOption;
+import org.apache.inlong.sort.base.metric.SinkMetricData;
+
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.streaming.api.functions.ProcessFunction;
+import org.apache.flink.util.Collector;
+import org.apache.hudi.client.WriteStatus;
+import org.apache.hudi.common.model.HoodieAvroRecord;
+import org.apache.hudi.common.model.HoodieKey;
+import org.apache.hudi.common.model.HoodieOperation;
+import org.apache.hudi.common.model.HoodieRecord;
+import org.apache.hudi.common.model.HoodieRecordLocation;
+import org.apache.hudi.common.model.HoodieRecordPayload;
+import org.apache.hudi.common.model.WriteOperationType;
+import org.apache.hudi.common.util.ObjectSizeCalculator;
+import org.apache.hudi.common.util.ValidationUtils;
+import org.apache.hudi.configuration.FlinkOptions;
+import org.apache.hudi.exception.HoodieException;
+import org.apache.hudi.index.HoodieIndex;
+import org.apache.hudi.sink.StreamWriteOperatorCoordinator;
+import org.apache.hudi.sink.common.AbstractStreamWriteFunction;
+import org.apache.hudi.sink.event.WriteMetadataEvent;
+import org.apache.hudi.table.action.commit.FlinkWriteHelper;
+import org.apache.hudi.util.StreamerUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.Random;
+import java.util.function.BiFunction;
+import java.util.stream.Collectors;
+
+/**
+ * Sink function to write the data to the underneath filesystem.
+ *
+ * <p><h2>Work Flow</h2>
+ *
+ * <p>The function firstly buffers the data as a batch of {@link HoodieRecord}s,
+ * It flushes(write) the records batch when the batch size exceeds the configured size {@link FlinkOptions#WRITE_BATCH_SIZE}
+ * or the total buffer size exceeds the configured size {@link FlinkOptions#WRITE_TASK_MAX_SIZE}
+ * or a Flink checkpoint starts. After a batch has been written successfully,
+ * the function notifies its operator coordinator {@link StreamWriteOperatorCoordinator} to mark a successful write.
+ *
+ * <p><h2>The Semantics</h2>
+ *
+ * <p>The task implements exactly-once semantics by buffering the data between checkpoints. The operator coordinator
+ * starts a new instant on the timeline when a checkpoint triggers, the coordinator checkpoints always
+ * start before its operator, so when this function starts a checkpoint, a REQUESTED instant already exists.
+ *
+ * <p>The function process thread blocks data buffering after the checkpoint thread finishes flushing the existing data buffer until
+ * the current checkpoint succeed and the coordinator starts a new instant. Any error triggers the job failure during the metadata committing,
+ * when the job recovers from a failure, the write function re-send the write metadata to the coordinator to see if these metadata
+ * can re-commit, thus if unexpected error happens during the instant committing, the coordinator would retry to commit when the job
+ * recovers.
+ *
+ * <p><h2>Fault Tolerance</h2>
+ *
+ * <p>The operator coordinator checks and commits the last instant then starts a new one after a checkpoint finished successfully.
+ * It rolls back any inflight instant before it starts a new instant, this means one hoodie instant only span one checkpoint,
+ * the write function blocks data buffer flushing for the configured checkpoint timeout
+ * before it throws exception, any checkpoint failure would finally trigger the job failure.
+ *
+ * <p>Note: The function task requires the input stream be shuffled by the file IDs.
+ *
+ * @param <I> Type of the input record
+ * @see StreamWriteOperatorCoordinator
+ *
+ * Copy from org.apache.hudi:hudi-flink1.15-bundle:0.12.3
+ */
+public class StreamWriteFunction<I> extends AbstractStreamWriteFunction<I> {
+
+    private static final long serialVersionUID = 1L;
+
+    private static final Logger LOG = LoggerFactory.getLogger(StreamWriteFunction.class);
+
+    /**
+     * Write buffer as buckets for a checkpoint. The key is bucket ID.
+     */
+    private transient Map<String, DataBucket> buckets;
+
+    private transient BiFunction<List<HoodieRecord>, String, List<WriteStatus>> writeFunction;
+
+    /**
+     * Total size tracer.
+     */
+    private transient TotalSizeTracer tracer;
+    private final MetricOption metricOption;
+    private SinkMetricData sinkMetricData;
+
+    /**
+     * Constructs a StreamingSinkFunction.
+     *
+     * @param config The config options
+     */
+    public StreamWriteFunction(Configuration config, MetricOption metricOption) {
+        super(config);
+        this.metricOption = metricOption;
+    }
+
+    @Override
+    public void open(Configuration parameters) throws IOException {

Review Comment:
   fix it ~ thx~



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

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

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


Re: [PR] [INLONG-10195][Sort] Hudi connector support audit ID [inlong]

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


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

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

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


Re: [PR] [INLONG-10195][Sort] Hudi connector support audit ID. [inlong]

Posted by "aloyszhang (via GitHub)" <gi...@apache.org>.
aloyszhang commented on code in PR #10231:
URL: https://github.com/apache/inlong/pull/10231#discussion_r1603126663


##########
inlong-sort/sort-flink/sort-flink-v1.15/sort-connectors/hudi/src/main/java/org/apache/inlong/sort/hudi/sink/utils/Pipelines.java:
##########
@@ -0,0 +1,468 @@
+/*
+ * 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.inlong.sort.hudi.sink.utils;
+
+import org.apache.inlong.sort.base.metric.MetricOption;
+import org.apache.inlong.sort.hudi.sink.StreamWriteOperator;
+import org.apache.inlong.sort.hudi.sink.append.AppendWriteOperator;
+import org.apache.inlong.sort.hudi.sink.bulk.BulkInsertWriteOperator;
+
+import org.apache.flink.api.common.functions.Partitioner;
+import org.apache.flink.api.common.typeinfo.TypeInformation;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.runtime.state.KeyGroupRangeAssignment;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.datastream.DataStreamSink;
+import org.apache.flink.streaming.api.functions.sink.SinkFunction;
+import org.apache.flink.streaming.api.operators.KeyedProcessOperator;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.planner.plan.nodes.exec.utils.ExecNodeUtil;
+import org.apache.flink.table.runtime.typeutils.InternalTypeInfo;
+import org.apache.flink.table.types.logical.RowType;
+import org.apache.hudi.common.model.ClusteringOperation;
+import org.apache.hudi.common.model.HoodieKey;
+import org.apache.hudi.common.model.HoodieRecord;
+import org.apache.hudi.configuration.FlinkOptions;
+import org.apache.hudi.configuration.OptionsResolver;
+import org.apache.hudi.sink.CleanFunction;
+import org.apache.hudi.sink.bootstrap.BootstrapOperator;
+import org.apache.hudi.sink.bootstrap.batch.BatchBootstrapOperator;
+import org.apache.hudi.sink.bucket.BucketBulkInsertWriterHelper;
+import org.apache.hudi.sink.bucket.BucketStreamWriteOperator;
+import org.apache.hudi.sink.bulk.RowDataKeyGen;
+import org.apache.hudi.sink.bulk.sort.SortOperatorGen;
+import org.apache.hudi.sink.clustering.ClusteringCommitEvent;
+import org.apache.hudi.sink.clustering.ClusteringCommitSink;
+import org.apache.hudi.sink.clustering.ClusteringOperator;
+import org.apache.hudi.sink.clustering.ClusteringPlanEvent;
+import org.apache.hudi.sink.clustering.ClusteringPlanOperator;
+import org.apache.hudi.sink.common.WriteOperatorFactory;
+import org.apache.hudi.sink.compact.CompactOperator;
+import org.apache.hudi.sink.compact.CompactionCommitEvent;
+import org.apache.hudi.sink.compact.CompactionCommitSink;
+import org.apache.hudi.sink.compact.CompactionPlanEvent;
+import org.apache.hudi.sink.compact.CompactionPlanOperator;
+import org.apache.hudi.sink.partitioner.BucketAssignFunction;
+import org.apache.hudi.sink.partitioner.BucketIndexPartitioner;
+import org.apache.hudi.sink.transform.RowDataToHoodieFunctions;
+import org.apache.hudi.table.format.FilePathUtils;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+/**
+ * Utilities to generate all kinds of sub-pipelines.
+ * <p>
+ * Copy from org.apache.hudi:hudi-flink1.15-bundle:0.12.3
+ */
+public class Pipelines {
+
+    /**
+     * Bulk insert the input dataset at once.
+     *
+     * <p>By default, the input dataset would shuffle by the partition path first then
+     * sort by the partition path before passing around to the write function.
+     * The whole pipeline looks like the following:
+     *
+     * <pre>
+     *      | input1 | ===\     /=== |sorter| === | task1 | (p1, p2)
+     *                   shuffle
+     *      | input2 | ===/     \=== |sorter| === | task2 | (p3, p4)
+     *
+     *      Note: Both input1 and input2's dataset come from partitions: p1, p2, p3, p4
+     * </pre>
+     *
+     * <p>The write task switches to new file handle each time it receives a record
+     * from the different partition path, the shuffle and sort would reduce small files.
+     *
+     * <p>The bulk insert should be run in batch execution mode.
+     *
+     * @param conf       The configuration
+     * @param rowType    The input row type
+     * @param dataStream The input data stream
+     * @return the bulk insert data stream sink
+     */
+    public static DataStreamSink<Object> bulkInsert(Configuration conf, RowType rowType, DataStream<RowData> dataStream,
+            MetricOption metricOption) {
+        WriteOperatorFactory<RowData> operatorFactory = BulkInsertWriteOperator.getFactory(conf, rowType, metricOption);
+        if (OptionsResolver.isBucketIndexType(conf)) {
+            String indexKeys = conf.getString(FlinkOptions.INDEX_KEY_FIELD);
+            int numBuckets = conf.getInteger(FlinkOptions.BUCKET_INDEX_NUM_BUCKETS);
+
+            BucketIndexPartitioner<HoodieKey> partitioner = new BucketIndexPartitioner<>(numBuckets, indexKeys);
+            RowDataKeyGen keyGen = RowDataKeyGen.instance(conf, rowType);
+            RowType rowTypeWithFileId = BucketBulkInsertWriterHelper.rowTypeWithFileId(rowType);
+            InternalTypeInfo<RowData> typeInfo = InternalTypeInfo.of(rowTypeWithFileId);
+
+            Map<String, String> bucketIdToFileId = new HashMap<>();
+            dataStream = dataStream.partitionCustom(partitioner, keyGen::getHoodieKey)
+                    .map(record -> BucketBulkInsertWriterHelper.rowWithFileId(bucketIdToFileId, keyGen, record,
+                            indexKeys, numBuckets), typeInfo)
+                    .setParallelism(conf.getInteger(FlinkOptions.WRITE_TASKS)); // same parallelism as write task to
+                                                                                // avoid shuffle
+            if (conf.getBoolean(FlinkOptions.WRITE_BULK_INSERT_SORT_INPUT)) {
+                SortOperatorGen sortOperatorGen = BucketBulkInsertWriterHelper.getFileIdSorterGen(rowTypeWithFileId);
+                dataStream = dataStream.transform("file_sorter", typeInfo, sortOperatorGen.createSortOperator())
+                        .setParallelism(conf.getInteger(FlinkOptions.WRITE_TASKS)); // same parallelism as write task to
+                                                                                    // avoid shuffle
+                ExecNodeUtil.setManagedMemoryWeight(dataStream.getTransformation(),
+                        conf.getInteger(FlinkOptions.WRITE_SORT_MEMORY) * 1024L * 1024L);
+            }
+            return dataStream
+                    .transform(opName("bucket_bulk_insert", conf), TypeInformation.of(Object.class), operatorFactory)
+                    .uid(opUID("bucket_bulk_insert", conf))
+                    .setParallelism(conf.getInteger(FlinkOptions.WRITE_TASKS))
+                    .addSink(DummySink.INSTANCE)
+                    .name("dummy");
+        }
+
+        final String[] partitionFields = FilePathUtils.extractPartitionKeys(conf);
+        if (partitionFields.length > 0) {
+            RowDataKeyGen rowDataKeyGen = RowDataKeyGen.instance(conf, rowType);
+            if (conf.getBoolean(FlinkOptions.WRITE_BULK_INSERT_SHUFFLE_INPUT)) {
+
+                // shuffle by partition keys
+                // use #partitionCustom instead of #keyBy to avoid duplicate sort operations,
+                // see BatchExecutionUtils#applyBatchExecutionSettings for details.
+                Partitioner<String> partitioner =
+                        (key, channels) -> KeyGroupRangeAssignment.assignKeyToParallelOperator(key,
+                                KeyGroupRangeAssignment.computeDefaultMaxParallelism(
+                                        conf.getInteger(FlinkOptions.WRITE_TASKS)),
+                                channels);
+                dataStream = dataStream.partitionCustom(partitioner, rowDataKeyGen::getPartitionPath);
+            }
+            if (conf.getBoolean(FlinkOptions.WRITE_BULK_INSERT_SORT_INPUT)) {
+                SortOperatorGen sortOperatorGen = new SortOperatorGen(rowType, partitionFields);
+                // sort by partition keys
+                dataStream = dataStream
+                        .transform("partition_key_sorter",
+                                InternalTypeInfo.of(rowType),
+                                sortOperatorGen.createSortOperator())
+                        .setParallelism(conf.getInteger(FlinkOptions.WRITE_TASKS));
+                ExecNodeUtil.setManagedMemoryWeight(dataStream.getTransformation(),
+                        conf.getInteger(FlinkOptions.WRITE_SORT_MEMORY) * 1024L * 1024L);
+            }
+        }
+        return dataStream
+                .transform(opName("hoodie_bulk_insert_write", conf),
+                        TypeInformation.of(Object.class),
+                        operatorFactory)
+                // follow the parallelism of upstream operators to avoid shuffle
+                .setParallelism(conf.getInteger(FlinkOptions.WRITE_TASKS))
+                .addSink(DummySink.INSTANCE)
+                .name("dummy");
+    }
+
+    /**
+     * Insert the dataset with append mode(no upsert or deduplication).
+     *
+     * <p>The input dataset would be rebalanced among the write tasks:
+     *
+     * <pre>
+     *      | input1 | ===\     /=== | task1 | (p1, p2, p3, p4)
+     *                   shuffle
+     *      | input2 | ===/     \=== | task2 | (p1, p2, p3, p4)
+     *
+     *      Note: Both input1 and input2's dataset come from partitions: p1, p2, p3, p4
+     * </pre>
+     *
+     * <p>The write task switches to new file handle each time it receives a record
+     * from the different partition path, so there may be many small files.
+     *
+     * @param conf       The configuration
+     * @param rowType    The input row type
+     * @param dataStream The input data stream
+     * @param bounded    Whether the input stream is bounded
+     * @return the appending data stream sink
+     */
+    public static DataStream<Object> append(
+            Configuration conf,
+            RowType rowType,
+            DataStream<RowData> dataStream,
+            boolean bounded,
+            MetricOption metricOption) {
+        if (!bounded) {
+            // In principle, the config should be immutable, but the boundedness
+            // is only visible when creating the sink pipeline.
+            conf.setBoolean(FlinkOptions.WRITE_BULK_INSERT_SORT_INPUT, false);
+        }
+        WriteOperatorFactory<RowData> operatorFactory = AppendWriteOperator.getFactory(conf, rowType, metricOption);
+
+        return dataStream
+                .transform(opName("hoodie_append_write", conf), TypeInformation.of(Object.class), operatorFactory)
+                .uid(opUID("hoodie_stream_write", conf))
+                .setParallelism(conf.getInteger(FlinkOptions.WRITE_TASKS));
+    }
+
+    /**
+     * Constructs bootstrap pipeline as streaming.
+     * The bootstrap operator loads the existing data index (primary key to file id mapping),
+     * then sends the indexing data set to subsequent operator(usually the bucket assign operator).
+     */
+    public static DataStream<HoodieRecord> bootstrap(
+            Configuration conf,
+            RowType rowType,
+            DataStream<RowData> dataStream) {
+        return bootstrap(conf, rowType, dataStream, false, false);
+    }
+
+    /**
+     * Constructs bootstrap pipeline.
+     * The bootstrap operator loads the existing data index (primary key to file id mapping),
+     * then send the indexing data set to subsequent operator(usually the bucket assign operator).
+     *
+     * @param conf       The configuration
+     * @param rowType    The row type
+     * @param dataStream The data stream
+     * @param bounded    Whether the source is bounded
+     * @param overwrite  Whether it is insert overwrite
+     */
+    public static DataStream<HoodieRecord> bootstrap(
+            Configuration conf,
+            RowType rowType,
+            DataStream<RowData> dataStream,
+            boolean bounded,
+            boolean overwrite) {
+        final boolean globalIndex = conf.getBoolean(FlinkOptions.INDEX_GLOBAL_ENABLED);
+        if (overwrite || OptionsResolver.isBucketIndexType(conf)) {
+            return rowDataToHoodieRecord(conf, rowType, dataStream);
+        } else if (bounded && !globalIndex && OptionsResolver.isPartitionedTable(conf)) {
+            return boundedBootstrap(conf, rowType, dataStream);
+        } else {
+            return streamBootstrap(conf, rowType, dataStream, bounded);
+        }
+    }
+
+    private static DataStream<HoodieRecord> streamBootstrap(
+            Configuration conf,
+            RowType rowType,
+            DataStream<RowData> dataStream,
+            boolean bounded) {
+        DataStream<HoodieRecord> dataStream1 = rowDataToHoodieRecord(conf, rowType, dataStream);
+
+        if (conf.getBoolean(FlinkOptions.INDEX_BOOTSTRAP_ENABLED) || bounded) {
+            dataStream1 = dataStream1
+                    .transform(
+                            "index_bootstrap",
+                            TypeInformation.of(HoodieRecord.class),
+                            new BootstrapOperator<>(conf))
+                    .setParallelism(
+                            conf.getOptional(FlinkOptions.INDEX_BOOTSTRAP_TASKS).orElse(dataStream1.getParallelism()))
+                    .uid(opUID("index_bootstrap", conf));
+        }
+
+        return dataStream1;
+    }
+
+    /**
+     * Constructs bootstrap pipeline for batch execution mode.
+     * The indexing data set is loaded before the actual data write
+     * in order to support batch UPSERT.
+     */
+    private static DataStream<HoodieRecord> boundedBootstrap(
+            Configuration conf,
+            RowType rowType,
+            DataStream<RowData> dataStream) {
+        final RowDataKeyGen rowDataKeyGen = RowDataKeyGen.instance(conf, rowType);
+        // shuffle by partition keys
+        dataStream = dataStream
+                .keyBy(rowDataKeyGen::getPartitionPath);
+
+        return rowDataToHoodieRecord(conf, rowType, dataStream)
+                .transform(
+                        "batch_index_bootstrap",
+                        TypeInformation.of(HoodieRecord.class),
+                        new BatchBootstrapOperator<>(conf))
+                .setParallelism(
+                        conf.getOptional(FlinkOptions.INDEX_BOOTSTRAP_TASKS).orElse(dataStream.getParallelism()))
+                .uid(opUID("batch_index_bootstrap", conf));
+    }
+
+    /**
+     * Transforms the row data to hoodie records.
+     */
+    public static DataStream<HoodieRecord> rowDataToHoodieRecord(Configuration conf, RowType rowType,
+            DataStream<RowData> dataStream) {
+        return dataStream.map(RowDataToHoodieFunctions.create(rowType, conf), TypeInformation.of(HoodieRecord.class))
+                .setParallelism(dataStream.getParallelism()).name("row_data_to_hoodie_record");
+    }
+
+    /**
+     * The streaming write pipeline.
+     *
+     * <p>The input dataset shuffles by the primary key first then
+     * shuffles by the file group ID before passing around to the write function.
+     * The whole pipeline looks like the following:
+     *
+     * <pre>
+     *      | input1 | ===\     /=== | bucket assigner | ===\     /=== | task1 |
+     *                   shuffle(by PK)                    shuffle(by bucket ID)
+     *      | input2 | ===/     \=== | bucket assigner | ===/     \=== | task2 |
+     *
+     *      Note: a file group must be handled by one write task to avoid write conflict.
+     * </pre>
+     *
+     * <p>The bucket assigner assigns the inputs to suitable file groups, the write task caches
+     * and flushes the data set to disk.
+     *
+     * @param conf       The configuration
+     * @param dataStream The input data stream
+     * @return the stream write data stream pipeline
+     */
+    public static DataStream<Object> hoodieStreamWrite(Configuration conf, DataStream<HoodieRecord> dataStream,
+            MetricOption metricOption) {
+        if (OptionsResolver.isBucketIndexType(conf)) {
+            WriteOperatorFactory<HoodieRecord> operatorFactory = BucketStreamWriteOperator.getFactory(conf);

Review Comment:
   Miss metricOption here



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

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

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


Re: [PR] [INLONG-10195][Sort] Hudi connector support audit ID [inlong]

Posted by "EMsnap (via GitHub)" <gi...@apache.org>.
EMsnap commented on code in PR #10231:
URL: https://github.com/apache/inlong/pull/10231#discussion_r1607525431


##########
inlong-sort/sort-flink/sort-flink-v1.15/sort-connectors/hudi/src/main/java/org/apache/inlong/sort/hudi/sink/StreamWriteFunction.java:
##########
@@ -0,0 +1,496 @@
+/*
+ * 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.inlong.sort.hudi.sink;
+
+import org.apache.inlong.sort.base.metric.MetricOption;
+import org.apache.inlong.sort.base.metric.SinkMetricData;
+
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.streaming.api.functions.ProcessFunction;
+import org.apache.flink.util.Collector;
+import org.apache.hudi.client.WriteStatus;
+import org.apache.hudi.common.model.HoodieAvroRecord;
+import org.apache.hudi.common.model.HoodieKey;
+import org.apache.hudi.common.model.HoodieOperation;
+import org.apache.hudi.common.model.HoodieRecord;
+import org.apache.hudi.common.model.HoodieRecordLocation;
+import org.apache.hudi.common.model.HoodieRecordPayload;
+import org.apache.hudi.common.model.WriteOperationType;
+import org.apache.hudi.common.util.ObjectSizeCalculator;
+import org.apache.hudi.common.util.ValidationUtils;
+import org.apache.hudi.configuration.FlinkOptions;
+import org.apache.hudi.exception.HoodieException;
+import org.apache.hudi.index.HoodieIndex;
+import org.apache.hudi.sink.StreamWriteOperatorCoordinator;
+import org.apache.hudi.sink.common.AbstractStreamWriteFunction;
+import org.apache.hudi.sink.event.WriteMetadataEvent;
+import org.apache.hudi.table.action.commit.FlinkWriteHelper;
+import org.apache.hudi.util.StreamerUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.Random;
+import java.util.function.BiFunction;
+import java.util.stream.Collectors;
+
+/**
+ * Sink function to write the data to the underneath filesystem.
+ *
+ * <p><h2>Work Flow</h2>
+ *
+ * <p>The function firstly buffers the data as a batch of {@link HoodieRecord}s,
+ * It flushes(write) the records batch when the batch size exceeds the configured size {@link FlinkOptions#WRITE_BATCH_SIZE}
+ * or the total buffer size exceeds the configured size {@link FlinkOptions#WRITE_TASK_MAX_SIZE}
+ * or a Flink checkpoint starts. After a batch has been written successfully,
+ * the function notifies its operator coordinator {@link StreamWriteOperatorCoordinator} to mark a successful write.
+ *
+ * <p><h2>The Semantics</h2>
+ *
+ * <p>The task implements exactly-once semantics by buffering the data between checkpoints. The operator coordinator
+ * starts a new instant on the timeline when a checkpoint triggers, the coordinator checkpoints always
+ * start before its operator, so when this function starts a checkpoint, a REQUESTED instant already exists.
+ *
+ * <p>The function process thread blocks data buffering after the checkpoint thread finishes flushing the existing data buffer until
+ * the current checkpoint succeed and the coordinator starts a new instant. Any error triggers the job failure during the metadata committing,
+ * when the job recovers from a failure, the write function re-send the write metadata to the coordinator to see if these metadata
+ * can re-commit, thus if unexpected error happens during the instant committing, the coordinator would retry to commit when the job
+ * recovers.
+ *
+ * <p><h2>Fault Tolerance</h2>
+ *
+ * <p>The operator coordinator checks and commits the last instant then starts a new one after a checkpoint finished successfully.
+ * It rolls back any inflight instant before it starts a new instant, this means one hoodie instant only span one checkpoint,
+ * the write function blocks data buffer flushing for the configured checkpoint timeout
+ * before it throws exception, any checkpoint failure would finally trigger the job failure.
+ *
+ * <p>Note: The function task requires the input stream be shuffled by the file IDs.
+ *
+ * @param <I> Type of the input record
+ * @see StreamWriteOperatorCoordinator
+ *
+ * Copy from org.apache.hudi:hudi-flink1.15-bundle:0.12.3
+ */
+public class StreamWriteFunction<I> extends AbstractStreamWriteFunction<I> {
+
+    private static final long serialVersionUID = 1L;
+
+    private static final Logger LOG = LoggerFactory.getLogger(StreamWriteFunction.class);
+
+    /**
+     * Write buffer as buckets for a checkpoint. The key is bucket ID.
+     */
+    private transient Map<String, DataBucket> buckets;
+
+    private transient BiFunction<List<HoodieRecord>, String, List<WriteStatus>> writeFunction;
+
+    /**
+     * Total size tracer.
+     */
+    private transient TotalSizeTracer tracer;
+    private final MetricOption metricOption;
+    private SinkMetricData sinkMetricData;
+
+    /**
+     * Constructs a StreamingSinkFunction.
+     *
+     * @param config The config options
+     */
+    public StreamWriteFunction(Configuration config, MetricOption metricOption) {
+        super(config);
+        this.metricOption = metricOption;
+    }
+
+    @Override
+    public void open(Configuration parameters) throws IOException {

Review Comment:
   ditto 



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

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

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


Re: [PR] [INLONG-10195][Sort] Hudi connector support audit ID [inlong]

Posted by "EMsnap (via GitHub)" <gi...@apache.org>.
EMsnap commented on code in PR #10231:
URL: https://github.com/apache/inlong/pull/10231#discussion_r1607525155


##########
inlong-sort/sort-flink/sort-flink-v1.15/sort-connectors/hudi/src/main/java/org/apache/inlong/sort/hudi/sink/bucket/BucketStreamWriteFunction.java:
##########
@@ -0,0 +1,185 @@
+/*
+ * 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.inlong.sort.hudi.sink.bucket;
+
+import org.apache.inlong.sort.base.metric.MetricOption;
+import org.apache.inlong.sort.base.metric.SinkMetricData;
+
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.runtime.state.FunctionInitializationContext;
+import org.apache.flink.streaming.api.functions.ProcessFunction;
+import org.apache.flink.util.Collector;
+import org.apache.hudi.common.model.HoodieKey;
+import org.apache.hudi.common.model.HoodieRecord;
+import org.apache.hudi.common.model.HoodieRecordLocation;
+import org.apache.hudi.configuration.FlinkOptions;
+import org.apache.hudi.index.bucket.BucketIdentifier;
+import org.apache.hudi.sink.StreamWriteFunction;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * A stream write function with bucket hash index.
+ *
+ * <p>The task holds a fresh new local index: {(partition + bucket number) &rarr fileId} mapping, this index
+ * is used for deciding whether the incoming records in an UPDATE or INSERT.
+ * The index is local because different partition paths have separate items in the index.
+ *
+ * @param <I> the input type
+ */
+public class BucketStreamWriteFunction<I> extends StreamWriteFunction<I> {
+
+    private static final Logger LOG = LoggerFactory.getLogger(BucketStreamWriteFunction.class);
+
+    private int parallelism;
+
+    private int bucketNum;
+
+    private String indexKeyFields;
+
+    /**
+     * BucketID to file group mapping in each partition.
+     * Map(partition -> Map(bucketId, fileID)).
+     */
+    private Map<String, Map<Integer, String>> bucketIndex;
+
+    /**
+     * Incremental bucket index of the current checkpoint interval,
+     * it is needed because the bucket type('I' or 'U') should be decided based on the committed files view,
+     * all the records in one bucket should have the same bucket type.
+     */
+    private Set<String> incBucketIndex;
+    private final MetricOption metricOption;
+    private SinkMetricData sinkMetricData;
+
+    /**
+     * Constructs a BucketStreamWriteFunction.
+     *
+     * @param config The config options
+     */
+    public BucketStreamWriteFunction(Configuration config, MetricOption metricOption) {
+        super(config);
+        this.metricOption = metricOption;
+    }
+
+    @Override
+    public void open(Configuration parameters) throws IOException {

Review Comment:
   where is the IOException thrown out ? 



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

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

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


Re: [PR] [INLONG-10195][Sort] Hudi connector support audit ID. [inlong]

Posted by "XiaoYou201 (via GitHub)" <gi...@apache.org>.
XiaoYou201 commented on code in PR #10231:
URL: https://github.com/apache/inlong/pull/10231#discussion_r1603203762


##########
inlong-sort/sort-flink/sort-flink-v1.15/sort-connectors/hudi/src/main/java/org/apache/inlong/sort/hudi/sink/utils/Pipelines.java:
##########
@@ -0,0 +1,468 @@
+/*
+ * 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.inlong.sort.hudi.sink.utils;
+
+import org.apache.inlong.sort.base.metric.MetricOption;
+import org.apache.inlong.sort.hudi.sink.StreamWriteOperator;
+import org.apache.inlong.sort.hudi.sink.append.AppendWriteOperator;
+import org.apache.inlong.sort.hudi.sink.bulk.BulkInsertWriteOperator;
+
+import org.apache.flink.api.common.functions.Partitioner;
+import org.apache.flink.api.common.typeinfo.TypeInformation;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.runtime.state.KeyGroupRangeAssignment;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.datastream.DataStreamSink;
+import org.apache.flink.streaming.api.functions.sink.SinkFunction;
+import org.apache.flink.streaming.api.operators.KeyedProcessOperator;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.planner.plan.nodes.exec.utils.ExecNodeUtil;
+import org.apache.flink.table.runtime.typeutils.InternalTypeInfo;
+import org.apache.flink.table.types.logical.RowType;
+import org.apache.hudi.common.model.ClusteringOperation;
+import org.apache.hudi.common.model.HoodieKey;
+import org.apache.hudi.common.model.HoodieRecord;
+import org.apache.hudi.configuration.FlinkOptions;
+import org.apache.hudi.configuration.OptionsResolver;
+import org.apache.hudi.sink.CleanFunction;
+import org.apache.hudi.sink.bootstrap.BootstrapOperator;
+import org.apache.hudi.sink.bootstrap.batch.BatchBootstrapOperator;
+import org.apache.hudi.sink.bucket.BucketBulkInsertWriterHelper;
+import org.apache.hudi.sink.bucket.BucketStreamWriteOperator;
+import org.apache.hudi.sink.bulk.RowDataKeyGen;
+import org.apache.hudi.sink.bulk.sort.SortOperatorGen;
+import org.apache.hudi.sink.clustering.ClusteringCommitEvent;
+import org.apache.hudi.sink.clustering.ClusteringCommitSink;
+import org.apache.hudi.sink.clustering.ClusteringOperator;
+import org.apache.hudi.sink.clustering.ClusteringPlanEvent;
+import org.apache.hudi.sink.clustering.ClusteringPlanOperator;
+import org.apache.hudi.sink.common.WriteOperatorFactory;
+import org.apache.hudi.sink.compact.CompactOperator;
+import org.apache.hudi.sink.compact.CompactionCommitEvent;
+import org.apache.hudi.sink.compact.CompactionCommitSink;
+import org.apache.hudi.sink.compact.CompactionPlanEvent;
+import org.apache.hudi.sink.compact.CompactionPlanOperator;
+import org.apache.hudi.sink.partitioner.BucketAssignFunction;
+import org.apache.hudi.sink.partitioner.BucketIndexPartitioner;
+import org.apache.hudi.sink.transform.RowDataToHoodieFunctions;
+import org.apache.hudi.table.format.FilePathUtils;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+/**
+ * Utilities to generate all kinds of sub-pipelines.
+ * <p>
+ * Copy from org.apache.hudi:hudi-flink1.15-bundle:0.12.3
+ */
+public class Pipelines {
+
+    /**
+     * Bulk insert the input dataset at once.
+     *
+     * <p>By default, the input dataset would shuffle by the partition path first then
+     * sort by the partition path before passing around to the write function.
+     * The whole pipeline looks like the following:
+     *
+     * <pre>
+     *      | input1 | ===\     /=== |sorter| === | task1 | (p1, p2)
+     *                   shuffle
+     *      | input2 | ===/     \=== |sorter| === | task2 | (p3, p4)
+     *
+     *      Note: Both input1 and input2's dataset come from partitions: p1, p2, p3, p4
+     * </pre>
+     *
+     * <p>The write task switches to new file handle each time it receives a record
+     * from the different partition path, the shuffle and sort would reduce small files.
+     *
+     * <p>The bulk insert should be run in batch execution mode.
+     *
+     * @param conf       The configuration
+     * @param rowType    The input row type
+     * @param dataStream The input data stream
+     * @return the bulk insert data stream sink
+     */
+    public static DataStreamSink<Object> bulkInsert(Configuration conf, RowType rowType, DataStream<RowData> dataStream,
+            MetricOption metricOption) {
+        WriteOperatorFactory<RowData> operatorFactory = BulkInsertWriteOperator.getFactory(conf, rowType, metricOption);
+        if (OptionsResolver.isBucketIndexType(conf)) {
+            String indexKeys = conf.getString(FlinkOptions.INDEX_KEY_FIELD);
+            int numBuckets = conf.getInteger(FlinkOptions.BUCKET_INDEX_NUM_BUCKETS);
+
+            BucketIndexPartitioner<HoodieKey> partitioner = new BucketIndexPartitioner<>(numBuckets, indexKeys);
+            RowDataKeyGen keyGen = RowDataKeyGen.instance(conf, rowType);
+            RowType rowTypeWithFileId = BucketBulkInsertWriterHelper.rowTypeWithFileId(rowType);
+            InternalTypeInfo<RowData> typeInfo = InternalTypeInfo.of(rowTypeWithFileId);
+
+            Map<String, String> bucketIdToFileId = new HashMap<>();
+            dataStream = dataStream.partitionCustom(partitioner, keyGen::getHoodieKey)
+                    .map(record -> BucketBulkInsertWriterHelper.rowWithFileId(bucketIdToFileId, keyGen, record,
+                            indexKeys, numBuckets), typeInfo)
+                    .setParallelism(conf.getInteger(FlinkOptions.WRITE_TASKS)); // same parallelism as write task to
+                                                                                // avoid shuffle
+            if (conf.getBoolean(FlinkOptions.WRITE_BULK_INSERT_SORT_INPUT)) {
+                SortOperatorGen sortOperatorGen = BucketBulkInsertWriterHelper.getFileIdSorterGen(rowTypeWithFileId);
+                dataStream = dataStream.transform("file_sorter", typeInfo, sortOperatorGen.createSortOperator())
+                        .setParallelism(conf.getInteger(FlinkOptions.WRITE_TASKS)); // same parallelism as write task to
+                                                                                    // avoid shuffle
+                ExecNodeUtil.setManagedMemoryWeight(dataStream.getTransformation(),
+                        conf.getInteger(FlinkOptions.WRITE_SORT_MEMORY) * 1024L * 1024L);
+            }
+            return dataStream
+                    .transform(opName("bucket_bulk_insert", conf), TypeInformation.of(Object.class), operatorFactory)
+                    .uid(opUID("bucket_bulk_insert", conf))
+                    .setParallelism(conf.getInteger(FlinkOptions.WRITE_TASKS))
+                    .addSink(DummySink.INSTANCE)
+                    .name("dummy");
+        }
+
+        final String[] partitionFields = FilePathUtils.extractPartitionKeys(conf);
+        if (partitionFields.length > 0) {
+            RowDataKeyGen rowDataKeyGen = RowDataKeyGen.instance(conf, rowType);
+            if (conf.getBoolean(FlinkOptions.WRITE_BULK_INSERT_SHUFFLE_INPUT)) {
+
+                // shuffle by partition keys
+                // use #partitionCustom instead of #keyBy to avoid duplicate sort operations,
+                // see BatchExecutionUtils#applyBatchExecutionSettings for details.
+                Partitioner<String> partitioner =
+                        (key, channels) -> KeyGroupRangeAssignment.assignKeyToParallelOperator(key,
+                                KeyGroupRangeAssignment.computeDefaultMaxParallelism(
+                                        conf.getInteger(FlinkOptions.WRITE_TASKS)),
+                                channels);
+                dataStream = dataStream.partitionCustom(partitioner, rowDataKeyGen::getPartitionPath);
+            }
+            if (conf.getBoolean(FlinkOptions.WRITE_BULK_INSERT_SORT_INPUT)) {
+                SortOperatorGen sortOperatorGen = new SortOperatorGen(rowType, partitionFields);
+                // sort by partition keys
+                dataStream = dataStream
+                        .transform("partition_key_sorter",
+                                InternalTypeInfo.of(rowType),
+                                sortOperatorGen.createSortOperator())
+                        .setParallelism(conf.getInteger(FlinkOptions.WRITE_TASKS));
+                ExecNodeUtil.setManagedMemoryWeight(dataStream.getTransformation(),
+                        conf.getInteger(FlinkOptions.WRITE_SORT_MEMORY) * 1024L * 1024L);
+            }
+        }
+        return dataStream
+                .transform(opName("hoodie_bulk_insert_write", conf),
+                        TypeInformation.of(Object.class),
+                        operatorFactory)
+                // follow the parallelism of upstream operators to avoid shuffle
+                .setParallelism(conf.getInteger(FlinkOptions.WRITE_TASKS))
+                .addSink(DummySink.INSTANCE)
+                .name("dummy");
+    }
+
+    /**
+     * Insert the dataset with append mode(no upsert or deduplication).
+     *
+     * <p>The input dataset would be rebalanced among the write tasks:
+     *
+     * <pre>
+     *      | input1 | ===\     /=== | task1 | (p1, p2, p3, p4)
+     *                   shuffle
+     *      | input2 | ===/     \=== | task2 | (p1, p2, p3, p4)
+     *
+     *      Note: Both input1 and input2's dataset come from partitions: p1, p2, p3, p4
+     * </pre>
+     *
+     * <p>The write task switches to new file handle each time it receives a record
+     * from the different partition path, so there may be many small files.
+     *
+     * @param conf       The configuration
+     * @param rowType    The input row type
+     * @param dataStream The input data stream
+     * @param bounded    Whether the input stream is bounded
+     * @return the appending data stream sink
+     */
+    public static DataStream<Object> append(
+            Configuration conf,
+            RowType rowType,
+            DataStream<RowData> dataStream,
+            boolean bounded,
+            MetricOption metricOption) {
+        if (!bounded) {
+            // In principle, the config should be immutable, but the boundedness
+            // is only visible when creating the sink pipeline.
+            conf.setBoolean(FlinkOptions.WRITE_BULK_INSERT_SORT_INPUT, false);
+        }
+        WriteOperatorFactory<RowData> operatorFactory = AppendWriteOperator.getFactory(conf, rowType, metricOption);
+
+        return dataStream
+                .transform(opName("hoodie_append_write", conf), TypeInformation.of(Object.class), operatorFactory)
+                .uid(opUID("hoodie_stream_write", conf))
+                .setParallelism(conf.getInteger(FlinkOptions.WRITE_TASKS));
+    }
+
+    /**
+     * Constructs bootstrap pipeline as streaming.
+     * The bootstrap operator loads the existing data index (primary key to file id mapping),
+     * then sends the indexing data set to subsequent operator(usually the bucket assign operator).
+     */
+    public static DataStream<HoodieRecord> bootstrap(
+            Configuration conf,
+            RowType rowType,
+            DataStream<RowData> dataStream) {
+        return bootstrap(conf, rowType, dataStream, false, false);
+    }
+
+    /**
+     * Constructs bootstrap pipeline.
+     * The bootstrap operator loads the existing data index (primary key to file id mapping),
+     * then send the indexing data set to subsequent operator(usually the bucket assign operator).
+     *
+     * @param conf       The configuration
+     * @param rowType    The row type
+     * @param dataStream The data stream
+     * @param bounded    Whether the source is bounded
+     * @param overwrite  Whether it is insert overwrite
+     */
+    public static DataStream<HoodieRecord> bootstrap(
+            Configuration conf,
+            RowType rowType,
+            DataStream<RowData> dataStream,
+            boolean bounded,
+            boolean overwrite) {
+        final boolean globalIndex = conf.getBoolean(FlinkOptions.INDEX_GLOBAL_ENABLED);
+        if (overwrite || OptionsResolver.isBucketIndexType(conf)) {
+            return rowDataToHoodieRecord(conf, rowType, dataStream);
+        } else if (bounded && !globalIndex && OptionsResolver.isPartitionedTable(conf)) {
+            return boundedBootstrap(conf, rowType, dataStream);
+        } else {
+            return streamBootstrap(conf, rowType, dataStream, bounded);
+        }
+    }
+
+    private static DataStream<HoodieRecord> streamBootstrap(
+            Configuration conf,
+            RowType rowType,
+            DataStream<RowData> dataStream,
+            boolean bounded) {
+        DataStream<HoodieRecord> dataStream1 = rowDataToHoodieRecord(conf, rowType, dataStream);
+
+        if (conf.getBoolean(FlinkOptions.INDEX_BOOTSTRAP_ENABLED) || bounded) {
+            dataStream1 = dataStream1
+                    .transform(
+                            "index_bootstrap",
+                            TypeInformation.of(HoodieRecord.class),
+                            new BootstrapOperator<>(conf))
+                    .setParallelism(
+                            conf.getOptional(FlinkOptions.INDEX_BOOTSTRAP_TASKS).orElse(dataStream1.getParallelism()))
+                    .uid(opUID("index_bootstrap", conf));
+        }
+
+        return dataStream1;
+    }
+
+    /**
+     * Constructs bootstrap pipeline for batch execution mode.
+     * The indexing data set is loaded before the actual data write
+     * in order to support batch UPSERT.
+     */
+    private static DataStream<HoodieRecord> boundedBootstrap(
+            Configuration conf,
+            RowType rowType,
+            DataStream<RowData> dataStream) {
+        final RowDataKeyGen rowDataKeyGen = RowDataKeyGen.instance(conf, rowType);
+        // shuffle by partition keys
+        dataStream = dataStream
+                .keyBy(rowDataKeyGen::getPartitionPath);
+
+        return rowDataToHoodieRecord(conf, rowType, dataStream)
+                .transform(
+                        "batch_index_bootstrap",
+                        TypeInformation.of(HoodieRecord.class),
+                        new BatchBootstrapOperator<>(conf))
+                .setParallelism(
+                        conf.getOptional(FlinkOptions.INDEX_BOOTSTRAP_TASKS).orElse(dataStream.getParallelism()))
+                .uid(opUID("batch_index_bootstrap", conf));
+    }
+
+    /**
+     * Transforms the row data to hoodie records.
+     */
+    public static DataStream<HoodieRecord> rowDataToHoodieRecord(Configuration conf, RowType rowType,
+            DataStream<RowData> dataStream) {
+        return dataStream.map(RowDataToHoodieFunctions.create(rowType, conf), TypeInformation.of(HoodieRecord.class))
+                .setParallelism(dataStream.getParallelism()).name("row_data_to_hoodie_record");
+    }
+
+    /**
+     * The streaming write pipeline.
+     *
+     * <p>The input dataset shuffles by the primary key first then
+     * shuffles by the file group ID before passing around to the write function.
+     * The whole pipeline looks like the following:
+     *
+     * <pre>
+     *      | input1 | ===\     /=== | bucket assigner | ===\     /=== | task1 |
+     *                   shuffle(by PK)                    shuffle(by bucket ID)
+     *      | input2 | ===/     \=== | bucket assigner | ===/     \=== | task2 |
+     *
+     *      Note: a file group must be handled by one write task to avoid write conflict.
+     * </pre>
+     *
+     * <p>The bucket assigner assigns the inputs to suitable file groups, the write task caches
+     * and flushes the data set to disk.
+     *
+     * @param conf       The configuration
+     * @param dataStream The input data stream
+     * @return the stream write data stream pipeline
+     */
+    public static DataStream<Object> hoodieStreamWrite(Configuration conf, DataStream<HoodieRecord> dataStream,
+            MetricOption metricOption) {
+        if (OptionsResolver.isBucketIndexType(conf)) {
+            WriteOperatorFactory<HoodieRecord> operatorFactory = BucketStreamWriteOperator.getFactory(conf);

Review Comment:
   fix it~, thx~



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

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

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