ahmedabu98 commented on code in PR #40134: URL: https://github.com/apache/beam/pull/40134#discussion_r4064852501
########## sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/cdc/sink/CommitDeltas.java: ########## @@ -0,0 +1,1015 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.beam.sdk.io.iceberg.cdc.sink; + +import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.MoreObjects.firstNonNull; + +import com.google.auto.value.AutoValue; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.function.BiConsumer; +import java.util.function.LongSupplier; +import org.apache.beam.sdk.coders.Coder; +import org.apache.beam.sdk.coders.KvCoder; +import org.apache.beam.sdk.coders.StringUtf8Coder; +import org.apache.beam.sdk.coders.VarIntCoder; +import org.apache.beam.sdk.coders.VarLongCoder; +import org.apache.beam.sdk.io.iceberg.IcebergCatalogConfig; +import org.apache.beam.sdk.io.iceberg.SerializableDataFile; +import org.apache.beam.sdk.io.iceberg.SerializableDeleteFile; +import org.apache.beam.sdk.io.iceberg.SnapshotInfo; +import org.apache.beam.sdk.io.iceberg.TableCache; +import org.apache.beam.sdk.metrics.Counter; +import org.apache.beam.sdk.metrics.Distribution; +import org.apache.beam.sdk.metrics.Metrics; +import org.apache.beam.sdk.schemas.AutoValueSchema; +import org.apache.beam.sdk.schemas.NoSuchSchemaException; +import org.apache.beam.sdk.schemas.SchemaRegistry; +import org.apache.beam.sdk.schemas.annotations.DefaultSchema; +import org.apache.beam.sdk.schemas.annotations.SchemaFieldNumber; +import org.apache.beam.sdk.state.BagState; +import org.apache.beam.sdk.state.StateSpec; +import org.apache.beam.sdk.state.StateSpecs; +import org.apache.beam.sdk.state.TimeDomain; +import org.apache.beam.sdk.state.Timer; +import org.apache.beam.sdk.state.TimerSpec; +import org.apache.beam.sdk.state.TimerSpecs; +import org.apache.beam.sdk.state.ValueState; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.transforms.GroupByKey; +import org.apache.beam.sdk.transforms.PTransform; +import org.apache.beam.sdk.transforms.ParDo; +import org.apache.beam.sdk.transforms.WithKeys; +import org.apache.beam.sdk.transforms.windowing.BoundedWindow; +import org.apache.beam.sdk.transforms.windowing.GlobalWindow; +import org.apache.beam.sdk.transforms.windowing.GlobalWindows; +import org.apache.beam.sdk.transforms.windowing.Window; +import org.apache.beam.sdk.values.KV; +import org.apache.beam.sdk.values.PCollection; +import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.annotations.VisibleForTesting; +import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Lists; +import org.apache.iceberg.AppendFiles; +import org.apache.iceberg.DataFile; +import org.apache.iceberg.DeleteFile; +import org.apache.iceberg.FileContent; +import org.apache.iceberg.PartitionSpec; +import org.apache.iceberg.RowDelta; +import org.apache.iceberg.Snapshot; +import org.apache.iceberg.SnapshotUpdate; +import org.apache.iceberg.SortOrder; +import org.apache.iceberg.Table; +import org.apache.iceberg.util.ThreadPools; +import org.checkerframework.checker.nullness.qual.Nullable; +import org.joda.time.Duration; +import org.joda.time.Instant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * The CDC sink's commit stage: commits each {@code (destination, window)}'s merged writer outputs + * (represented as {@link ShardDeltaFiles}) as a single Iceberg snapshot, in ascending window-end + * order. Re-keys by destination, gathers all shards per {@code (dest, window)}, captures the window + * end, then re-windows into the global window for the stateful {@link OrderedCommitFn}. + * + * <p>Each commit writes the window's end millis to the snapshot summary as an idempotency token, + * keyed by the sink's unique {@code sinkId}. The committer recovers it by scanning snapshot + * ancestry: once on first touch of a destination, and again on every commit fire. Any window whose + * end is at or below the recovered token has already been committed, so it is skipped. + */ +class CommitDeltas + extends PTransform<PCollection<ShardDeltaFiles>, PCollection<KV<String, SnapshotInfo>>> { + + private static final Logger LOG = LoggerFactory.getLogger(CommitDeltas.class); + + // test-only attributes + @VisibleForTesting static volatile @Nullable Runnable preCommitHookForTest = null; + @VisibleForTesting static volatile @Nullable BiConsumer<Long, List<Long>> onFireForTest = null; + + private final IcebergCatalogConfig catalogConfig; + private final String sinkId; + private final Map<String, String> snapshotProperties; + private final long heartbeatMillis; + + /** The expansion's runId. */ + private final String runId; + + private Clock clock = System::currentTimeMillis; + + @VisibleForTesting + CommitDeltas(IcebergCatalogConfig catalogConfig, String sinkId) { + this(catalogConfig, sinkId, null, null); + } + + @VisibleForTesting + CommitDeltas( + IcebergCatalogConfig catalogConfig, + String sinkId, + @Nullable Map<String, String> snapshotProperties, + @Nullable Long tokenHeartbeatMillis) { + this( + catalogConfig, + sinkId, + snapshotProperties, + tokenHeartbeatMillis, + UUID.randomUUID().toString()); + } + + CommitDeltas( + IcebergCatalogConfig catalogConfig, + String sinkId, + @Nullable Map<String, String> snapshotProperties, + @Nullable Long tokenHeartbeatMillis, + String runId) { + this.catalogConfig = catalogConfig; + this.sinkId = sinkId; + this.snapshotProperties = + snapshotProperties == null ? Collections.emptyMap() : snapshotProperties; + this.heartbeatMillis = tokenHeartbeatMillis == null ? 0L : tokenHeartbeatMillis; + this.runId = runId; + } + + /** Overrides the committer's clock to test skew deterministically. */ + @VisibleForTesting + CommitDeltas withClockForTest(Clock clock) { + this.clock = clock; + return this; + } + + @Override + public PCollection<KV<String, SnapshotInfo>> expand(PCollection<ShardDeltaFiles> input) { + boolean streaming = input.isBounded() == PCollection.IsBounded.UNBOUNDED; + return input + .apply("KeyByDestination", WithKeys.of(ShardDeltaFiles::getTableIdentifierString)) + .setCoder(KvCoder.of(StringUtf8Coder.of(), ShardDeltaFiles.coder())) + // One element per (dest, window): every shard's output for the pair. + .apply("GatherShardsPerWindow", GroupByKey.create()) Review Comment: We already handle late data upstream in CommitWindows, so we don't produce any late `ShardDeltaFiles` 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: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
