ahmedabu98 commented on code in PR #40030:
URL: https://github.com/apache/beam/pull/40030#discussion_r4035775569


##########
sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/cdc/sink/AssignCdcKeys.java:
##########
@@ -0,0 +1,361 @@
+/*
+ * 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 java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import org.apache.beam.sdk.coders.ByteArrayCoder;
+import org.apache.beam.sdk.coders.CoderException;
+import org.apache.beam.sdk.coders.KvCoder;
+import org.apache.beam.sdk.coders.RowCoder;
+import org.apache.beam.sdk.io.iceberg.DynamicDestinations;
+import org.apache.beam.sdk.io.iceberg.IcebergCatalogConfig;
+import org.apache.beam.sdk.metrics.Counter;
+import org.apache.beam.sdk.metrics.Metrics;
+import org.apache.beam.sdk.schemas.Schema;
+import org.apache.beam.sdk.schemas.transforms.providers.ErrorHandling;
+import org.apache.beam.sdk.transforms.DoFn;
+import org.apache.beam.sdk.transforms.PTransform;
+import org.apache.beam.sdk.transforms.ParDo;
+import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
+import org.apache.beam.sdk.transforms.windowing.PaneInfo;
+import org.apache.beam.sdk.util.CoderUtils;
+import org.apache.beam.sdk.values.KV;
+import org.apache.beam.sdk.values.PCollection;
+import org.apache.beam.sdk.values.PCollectionTuple;
+import org.apache.beam.sdk.values.Row;
+import org.apache.beam.sdk.values.TupleTag;
+import org.apache.beam.sdk.values.TupleTagList;
+import org.apache.beam.sdk.values.ValueInSingleWindow;
+import org.apache.beam.sdk.values.ValueKind;
+import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.joda.time.Instant;
+
+/**
+ * Assigns a sort key to input {@link Row}s and groups by destination and 
shard keys, outputting
+ * {@code KV<DestinationShard, KV<sortKey, CdcRecord>>}.
+ *
+ * <p>For each element this:
+ *
+ * <ol>
+ *   <li>resolves the destination string from the raw element;
+ *   <li>resolves the element's {@link ValueKind};
+ *   <li>in upsert mode, drops {@code UPDATE_BEFORE} records;
+ *   <li>reads the sequence number from {@link 
CdcWriteConfig#getSequenceNumberColumn()};
+ *   <li>takes the row to write from {@link DynamicDestinations#getData}, 
which excludes the control
+ *       columns read above;
+ *   <li>resolves and validates the destination table through {@link 
TableSetup};
+ *   <li>encodes the primary key to bytes, which feed both the shard hash and 
the sort key;
+ *   <li>computes the deterministic shard, according to {@code numShards} and 
{@code
+ *       shardsPerPartition}
+ * </ol>
+ *
+ * <p>When {@link CdcWriteConfig#getErrorHandling()} is enabled, a 
record-level failure (unknown
+ * change type, missing/null sequence number, null equality value, an 
unresolvable destination) is
+ * diverted to the {@link #FAILED} output as an {@link 
ErrorHandling#errorSchema} row ({@code
+ * failed_row}, {@code error_message}). When error handling is disabled, the 
transform fails
+ * instead.
+ */
+final class AssignCdcKeys extends PTransform<PCollection<Row>, 
PCollectionTuple> {
+
+  static final TupleTag<KV<DestinationShard, KV<byte[], CdcRecord>>> KEYED = 
new TupleTag<>() {};
+  static final TupleTag<Row> FAILED = new TupleTag<Row>() {};
+
+  private final IcebergCatalogConfig catalogConfig;
+  private final CdcWriteConfig config;
+  private final DynamicDestinations destinations;
+  private final String runId;
+
+  AssignCdcKeys(
+      IcebergCatalogConfig catalogConfig,
+      CdcWriteConfig config,
+      DynamicDestinations destinations,
+      String runId) {
+    this.catalogConfig = catalogConfig;
+    this.config = config;
+    this.destinations = destinations;
+    this.runId = runId;
+  }
+
+  @Override
+  public PCollectionTuple expand(PCollection<Row> input) {
+    Schema inputSchema = input.getSchema();
+    Schema errorSchema = ErrorHandling.errorSchema(inputSchema);
+    Schema cdcDataSchema = destinations.getDataSchema();
+    PCollectionTuple outputs =
+        input.apply(
+            "AssignKeys",
+            ParDo.of(
+                    new AssignFn(
+                        new TableSetup(catalogConfig, config, destinations, 
runId),
+                        config,
+                        destinations,
+                        errorSchema))
+                .withOutputTags(KEYED, TupleTagList.of(FAILED)));
+    outputs
+        .get(KEYED)
+        .setCoder(
+            KvCoder.of(
+                DestinationShard.coder(),
+                KvCoder.of(ByteArrayCoder.of(), 
CdcRecordCoder.of(cdcDataSchema))));
+    outputs.get(FAILED).setCoder(RowCoder.of(errorSchema));
+    return outputs;
+  }
+
+  /** Per-record entry point, running the eight steps listed in the main 
javadoc above. */
+  private static final class AssignFn
+      extends DoFn<Row, KV<DestinationShard, KV<byte[], CdcRecord>>> {
+
+    private final TableSetup tableSetup;
+    private final CdcWriteConfig config;
+    private final DynamicDestinations destinations;
+    private final Schema errorSchema;
+    private final int numShards;
+    private final int shardsPerPartition;
+    private final Counter failedRecords = Metrics.counter(AssignCdcKeys.class, 
"failedRecords");
+    private final Counter upsertUpdateBeforeDropped =
+        Metrics.counter(AssignCdcKeys.class, "upsertUpdateBeforeDropped");
+
+    /** The control columns' positions in the current source schema. */
+    private transient @MonotonicNonNull ControlColumns controls;
+
+    AssignFn(
+        TableSetup tableSetup,
+        CdcWriteConfig config,
+        DynamicDestinations destinations,
+        Schema errorSchema) {
+      this.tableSetup = tableSetup;
+      this.config = config;
+      this.destinations = destinations;
+      this.errorSchema = errorSchema;
+      this.numShards = config.getNumShards();
+      this.shardsPerPartition = config.getShardsPerPartition();
+    }
+
+    @ProcessElement
+    public void processElement(
+        @Element Row element,
+        ValueKind elementKind,
+        @Timestamp Instant timestamp,
+        BoundedWindow window,
+        PaneInfo pane,
+        MultiOutputReceiver out) {
+      try {
+        Schema schema = element.getSchema();
+        String destString =
+            destinations.getTableStringIdentifier(
+                ValueInSingleWindow.of(element, timestamp, window, pane));
+
+        // Resolve the control columns' positions once per source schema. (The 
local lets the
+        // nullness checker prove non-nullness, which it cannot for the field.)
+        ControlColumns cols = controls;
+        if (cols == null || !cols.matches(schema)) {
+          cols = ControlColumns.of(schema, config);
+          controls = cols;
+        }
+
+        ValueKind kind = resolveKind(element, cols, elementKind);
+        if (config.getUpsert() && kind == ValueKind.UPDATE_BEFORE) {
+          upsertUpdateBeforeDropped.inc();
+          return;
+        }
+        long seq = readSeq(element, cols, kind);
+
+        Row data = destinations.getData(element);
+        TableSetup.Dest dest = tableSetup.get(destString, data.getSchema());
+        requireNonNullEqualityValues(dest, data);
+        byte[] pkBytes = encodePk(dest, data);
+
+        out.get(KEYED)
+            .output(
+                KV.of(
+                    DestinationShard.of(destString, shardFor(dest, data, 
pkBytes)),
+                    KV.of(CdcSortKey.encode(pkBytes, seq, kind), 
CdcRecord.of(data, kind, seq))));
+      } catch (TableSetup.TableConfigException e) {
+        throw e;

Review Comment:
   Removed this because we're now only catching CdcRecordExceptions



-- 
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]

Reply via email to