Guosmilesmile commented on code in PR #18144:
URL: https://github.com/apache/iceberg/pull/18144#discussion_r4443930511


##########
flink/v2.3/flink/src/main/java/org/apache/iceberg/flink/source/lookup/IcebergFullCachingLookupFunction.java:
##########
@@ -0,0 +1,231 @@
+/*
+ * 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.iceberg.flink.source.lookup;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.MetricGroup;
+import org.apache.flink.table.data.GenericRowData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.data.binary.BinaryRowData;
+import org.apache.flink.table.functions.FunctionContext;
+import org.apache.flink.table.functions.LookupFunction;
+import org.apache.flink.table.runtime.typeutils.RowDataSerializer;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.RowType;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.Snapshot;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.TableProperties;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.flink.FlinkRowData;
+import org.apache.iceberg.flink.FlinkSchemaUtil;
+import org.apache.iceberg.flink.TableLoader;
+import org.apache.iceberg.io.CloseableIterable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A lookup function that serves every lookup from an in-memory cache of the 
rows of an Iceberg
+ * table, after projection and pushed-down filters are applied.
+ *
+ * <p>The cache is loaded from the current snapshot either when the function 
is opened or on the
+ * first lookup, depending on {@link 
IcebergLookupOptions#FULL_CACHE_EAGER_LOAD}. It is never
+ * refreshed, so later changes to the table are not visible.
+ */
+@Internal
+public class IcebergFullCachingLookupFunction extends LookupFunction {
+
+  private static final Logger LOG = 
LoggerFactory.getLogger(IcebergFullCachingLookupFunction.class);
+
+  private static final String METRIC_GROUP = "cache";
+  private static final long UNINITIALIZED = -1L;
+
+  private final TableLoader tableLoader;
+  private final RowType projectedRowType;
+  private final int[] lookupKeyIndexes;
+  private final List<Expression> pushedFilters;
+  private final boolean caseSensitive;
+  private final boolean eagerLoad;
+
+  private transient Table table;
+  private transient IcebergLookupReader reader;
+  private transient RowDataSerializer rowSerializer;
+  private transient RowDataSerializer keySerializer;
+  private transient RowData.FieldGetter[] keyGetters;
+  private transient InMemoryLookupCache cache;
+
+  private transient Counter missCounter;
+  private transient Counter loadCounter;
+  private transient Counter loadFailuresCounter;
+  private transient volatile long currentSnapshotId;
+  private transient volatile long cachedRecords;
+  private transient volatile long latestLoadTimeMs;
+
+  public IcebergFullCachingLookupFunction(
+      TableLoader tableLoader,
+      RowType projectedRowType,
+      int[] lookupKeyIndexes,
+      List<Expression> pushedFilters,
+      boolean caseSensitive,
+      boolean eagerLoad) {
+    this.tableLoader = tableLoader;
+    this.projectedRowType = projectedRowType;
+    this.lookupKeyIndexes = lookupKeyIndexes;
+    this.pushedFilters = pushedFilters;
+    this.caseSensitive = caseSensitive;
+    this.eagerLoad = eagerLoad;
+  }
+
+  @Override
+  public void open(FunctionContext context) throws Exception {
+    super.open(context);
+    LOG.info(
+        "IcebergFullCachingLookupFunction opening, projected fields={}, 
lookupKeyIndexes={}",
+        projectedRowType.getFieldNames(),
+        Arrays.toString(lookupKeyIndexes));
+
+    MetricGroup metricGroup = context.getMetricGroup().addGroup(METRIC_GROUP);
+    this.missCounter = metricGroup.counter("missCount");
+    this.loadCounter = metricGroup.counter("loadCount");
+    this.loadFailuresCounter = metricGroup.counter("numLoadFailures");
+    this.currentSnapshotId = IcebergLookupReader.CURRENT_SNAPSHOT;
+    this.cachedRecords = 0L;
+    this.latestLoadTimeMs = UNINITIALIZED;
+    metricGroup.gauge("snapshotId", () -> currentSnapshotId);
+    metricGroup.gauge("numCachedRecords", () -> cachedRecords);
+    metricGroup.gauge("latestLoadTime", () -> latestLoadTimeMs);
+
+    tableLoader.open();
+    this.table = tableLoader.loadTable();
+
+    Schema icebergProjection =
+        FlinkSchemaUtil.convert(table.schema(), 
FlinkSchemaUtil.toResolvedSchema(projectedRowType));
+
+    createAccessors();
+
+    String nameMapping = 
table.properties().get(TableProperties.DEFAULT_NAME_MAPPING);
+    this.reader =
+        new IcebergLookupReader(
+            table, icebergProjection, pushedFilters, caseSensitive, 
nameMapping);
+
+    if (eagerLoad) {
+      loadCache();
+    }
+  }
+
+  /**
+   * Returns the cached rows for the key. The returned collection and its rows 
are shared with the
+   * cache, so they must not be modified.
+   */
+  @Override
+  public Collection<RowData> lookup(RowData keyRow) throws IOException {
+    if (cache == null) {
+      loadCache();
+    }
+
+    List<RowData> hit = cache.get(keySerializer.toBinaryRow(keyRow));
+    if (hit == null) {
+      missCounter.inc();
+      return Collections.emptyList();
+    }
+
+    return hit;
+  }
+
+  @Override
+  public void close() throws Exception {
+    try {
+      tableLoader.close();
+    } finally {
+      if (cache != null) {
+        cache.close();
+      }
+
+      super.close();
+    }
+  }
+
+  private void loadCache() throws IOException {
+    table.refresh();
+    Snapshot snapshot = table.currentSnapshot();
+    long snapshotId =
+        snapshot == null ? IcebergLookupReader.CURRENT_SNAPSHOT : 
snapshot.snapshotId();

Review Comment:
   Yes, add a UT createEmptyProbeAndUnreadableDimTable for this case.



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


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to