ibzib commented on a change in pull request #16130:
URL: https://github.com/apache/beam/pull/16130#discussion_r764277870



##########
File path: 
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/Caches.java
##########
@@ -0,0 +1,285 @@
+/*
+ * 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.fn.harness;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Objects;
+import java.util.Set;
+import java.util.function.Function;
+import org.apache.beam.sdk.options.PipelineOptions;
+import org.apache.beam.sdk.options.SdkHarnessOptions;
+import 
org.apache.beam.vendor.guava.v26_0_jre.com.google.common.annotations.VisibleForTesting;
+import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.Sets;
+import 
org.apache.beam.vendor.guava.v26_0_jre.com.google.common.util.concurrent.MoreExecutors;
+import org.cache2k.Cache2kBuilder;
+import org.cache2k.operation.Weigher;
+import org.github.jamm.MemoryMeter;
+
+/** Utility methods used to instantiate and operate over cache instances. */
+@SuppressWarnings("nullness")
+public final class Caches {
+
+  /** A cache that never stores any values. */
+  public static <K, V> Cache<K, V> noop() {

Review comment:
       Why do we need this?

##########
File path: 
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/Caches.java
##########
@@ -0,0 +1,285 @@
+/*
+ * 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.fn.harness;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Objects;
+import java.util.Set;
+import java.util.function.Function;
+import org.apache.beam.sdk.options.PipelineOptions;
+import org.apache.beam.sdk.options.SdkHarnessOptions;
+import 
org.apache.beam.vendor.guava.v26_0_jre.com.google.common.annotations.VisibleForTesting;
+import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.Sets;
+import 
org.apache.beam.vendor.guava.v26_0_jre.com.google.common.util.concurrent.MoreExecutors;
+import org.cache2k.Cache2kBuilder;
+import org.cache2k.operation.Weigher;
+import org.github.jamm.MemoryMeter;
+
+/** Utility methods used to instantiate and operate over cache instances. */
+@SuppressWarnings("nullness")
+public final class Caches {
+
+  /** A cache that never stores any values. */
+  public static <K, V> Cache<K, V> noop() {
+    return new SubCacheable<K, V>() {
+      @Override
+      public V peek(K key) {
+        return null;
+      }
+
+      @Override
+      public V computeIfAbsent(K key, Function<K, V> loadingFunction) {
+        return loadingFunction.apply(key);
+      }
+
+      @Override
+      public void put(K key, V value) {}
+
+      @Override
+      public void clear() {}
+
+      @Override
+      public void remove(K key) {}
+
+      @Override
+      public Set<K> keys() {
+        return Collections.emptySet();
+      }
+    };
+  }
+
+  /**
+   * Uses the specified {@link PipelineOptions} to configure and return a 
cache instance based upon
+   * parameters within {@link SdkHarnessOptions}.
+   */
+  public static <K, V> Cache<K, V> fromOptions(PipelineOptions options) {
+    // We specifically use cache2k since it allows for recursive 
computeIfAbsent calls
+    // preventing deadlock from occurring when a loading function mutates the 
underlying cache
+    org.cache2k.Cache<Object, Object> cache =
+        Cache2kBuilder.forUnknownTypes()
+            .maximumWeight(
+                options.as(SdkHarnessOptions.class).getMaxCacheMemoryUsageMb() 
* 1024L * 1024L)
+            .weigher(
+                new Weigher<Object, Object>() {
+                  private final MemoryMeter memoryMeter = 
MemoryMeter.builder().build();
+
+                  @Override
+                  public int weigh(Object key, Object value) {
+                    long size = memoryMeter.measureDeep(key) + 
memoryMeter.measureDeep(value);
+                    return size > Integer.MAX_VALUE ? Integer.MAX_VALUE : 
(int) size;
+                  }
+                })
+            .storeByReference(true)
+            .executor(MoreExecutors.directExecutor())
+            .build();
+
+    return (Cache<K, V>) forCache(cache);
+  }
+
+  /**
+   * Returns a view of a cache that operates on keys with a specified key 
prefix.
+   *
+   * <p>All lookups, insertions, and removals into the parent {@link Cache} 
will be prefixed by the
+   * specified prefixes.
+   *
+   * <p>Operations which operate over the entire caches contents such as 
{@link Cache#clear} only
+   * operate over keys with the specified prefixes.
+   */
+  public static <K, V> Cache<K, V> subCache(
+      Cache<?, ?> cache, Object keyPrefix, Object... additionalKeyPrefix) {
+    if (cache instanceof SubCache) {
+      return new SubCache<>(
+          ((SubCache<?, ?>) cache).cache,
+          ((SubCache<?, ?>) cache).keyPrefix.subKey(keyPrefix, 
additionalKeyPrefix));
+    } else if (cache instanceof SubCacheable) {
+      return new SubCache<>((SubCacheable<?, ?>) cache, 
CompositeKey.ROOT.subKey(keyPrefix));
+    }
+    throw new UnsupportedOperationException("An unsupported type of cache was 
passed.");
+  }
+
+  /** A cache that never evicts any values. */
+  public static <K, V> Cache<K, V> eternal() {
+    // We specifically use cache2k since it allows for recursive 
computeIfAbsent calls
+    // preventing deadlock from occurring when a loading function mutates the 
underlying cache
+    org.cache2k.Cache<Object, Object> cache =
+        Cache2kBuilder.forUnknownTypes()
+            .entryCapacity(Long.MAX_VALUE)
+            .storeByReference(true)
+            .executor(MoreExecutors.directExecutor())
+            .build();
+    return (Cache<K, V>) forCache(cache);
+  }
+
+  private static Cache<Object, Object> forCache(org.cache2k.Cache<Object, 
Object> cache) {
+    return new SubCacheable<Object, Object>() {
+      @Override
+      public Object peek(Object key) {
+        return cache.get(key);
+      }
+
+      @Override
+      public Object computeIfAbsent(Object key, Function<Object, Object> 
loadingFunction) {
+        return cache.computeIfAbsent(key, loadingFunction);
+      }
+
+      @Override
+      public void put(Object key, Object value) {
+        cache.put(key, value);
+      }
+
+      @Override
+      public void clear() {
+        cache.clear();
+      }
+
+      @Override
+      public void remove(Object key) {
+        cache.remove(key);
+      }
+
+      @Override
+      public Set<Object> keys() {
+        return cache.keys();
+      }
+    };
+  }
+
+  /**
+   * Additional operations necessary for a top level cache to support 
sub-caching.
+   *
+   * <p>Visibility is restricted to prevent usage of these methods outside of 
this class.
+   */
+  private interface SubCacheable<K, V> extends Cache<K, V> {
+    Set<K> keys();
+  }
+
+  /**
+   * A view of a cache that operates on keys with a specified key prefix.
+   *
+   * <p>All lookups, insertions, and removals into the parent {@link Cache} 
will be prefixed by the
+   * specified prefixes.
+   *
+   * <p>Operations which operate over the entire caches contents such as 
{@link Cache#clear} only
+   * operate over keys with the specified prefixes.
+   */
+  private static class SubCache<K, V> implements Cache<K, V> {
+    private final SubCacheable<CompositeKey, Object> cache;
+    private final CompositeKey keyPrefix;
+
+    SubCache(SubCacheable<?, ?> cache, CompositeKey keyPrefix) {
+      this.cache = (SubCacheable<CompositeKey, Object>) cache;
+      this.keyPrefix = keyPrefix;
+    }
+
+    @Override
+    public V peek(K key) {
+      return (V) cache.peek(keyPrefix.subKey(key));
+    }
+
+    @Override
+    public V computeIfAbsent(K key, Function<K, V> loadingFunction) {
+      return (V)
+          cache.computeIfAbsent(
+              keyPrefix.subKey(key),
+              new Function<CompositeKey, Object>() {
+
+                @Override
+                public Object apply(CompositeKey o) {
+                  return loadingFunction.apply((K) 
o.keyParts[o.keyParts.length - 1]);
+                }
+              });
+    }
+
+    @Override
+    public void put(K key, V value) {
+      cache.put(keyPrefix.subKey(key), value);
+    }
+
+    @Override
+    public void clear() {
+      for (Object key : Sets.filter(cache.keys(), (Object o) -> 
keyPrefix.isProperPrefixOf(o))) {
+        cache.remove((CompositeKey) key);
+      }
+    }
+
+    @Override
+    public void remove(K key) {
+      cache.remove(keyPrefix.subKey(key));
+    }
+  }
+
+  /** A tuple of key parts used to represent a key within a cache. */
+  @VisibleForTesting
+  static class CompositeKey {
+    public static final CompositeKey ROOT = new CompositeKey(new Object[0]);
+    Object[] keyParts;
+
+    private CompositeKey(Object[] keyParts) {
+      this.keyParts = keyParts;
+    }
+
+    CompositeKey subKey(Object suffix, Object... additionalSuffixes) {
+      Object[] subKey = new Object[keyParts.length + 1 + 
additionalSuffixes.length];
+      System.arraycopy(keyParts, 0, subKey, 0, keyParts.length);
+      subKey[keyParts.length] = suffix;
+      System.arraycopy(
+          additionalSuffixes, 0, subKey, keyParts.length + 1, 
additionalSuffixes.length);
+      return new CompositeKey(subKey);
+    }
+
+    boolean isProperPrefixOf(Object possiblySuffix) {

Review comment:
       Nit: I don't think "suffix" is the right word for the argument here (if 
A is a prefix of B, then `B = A + suffix`) but I'm unsure of what the right 
word is. See 
https://english.stackexchange.com/questions/421424/what-is-the-opposite-of-a-prefix

##########
File path: 
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/Caches.java
##########
@@ -0,0 +1,285 @@
+/*
+ * 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.fn.harness;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Objects;
+import java.util.Set;
+import java.util.function.Function;
+import org.apache.beam.sdk.options.PipelineOptions;
+import org.apache.beam.sdk.options.SdkHarnessOptions;
+import 
org.apache.beam.vendor.guava.v26_0_jre.com.google.common.annotations.VisibleForTesting;
+import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.Sets;
+import 
org.apache.beam.vendor.guava.v26_0_jre.com.google.common.util.concurrent.MoreExecutors;
+import org.cache2k.Cache2kBuilder;
+import org.cache2k.operation.Weigher;
+import org.github.jamm.MemoryMeter;
+
+/** Utility methods used to instantiate and operate over cache instances. */
+@SuppressWarnings("nullness")
+public final class Caches {
+
+  /** A cache that never stores any values. */
+  public static <K, V> Cache<K, V> noop() {
+    return new SubCacheable<K, V>() {
+      @Override
+      public V peek(K key) {
+        return null;
+      }
+
+      @Override
+      public V computeIfAbsent(K key, Function<K, V> loadingFunction) {
+        return loadingFunction.apply(key);
+      }
+
+      @Override
+      public void put(K key, V value) {}
+
+      @Override
+      public void clear() {}
+
+      @Override
+      public void remove(K key) {}
+
+      @Override
+      public Set<K> keys() {
+        return Collections.emptySet();
+      }
+    };
+  }
+
+  /**
+   * Uses the specified {@link PipelineOptions} to configure and return a 
cache instance based upon
+   * parameters within {@link SdkHarnessOptions}.
+   */
+  public static <K, V> Cache<K, V> fromOptions(PipelineOptions options) {
+    // We specifically use cache2k since it allows for recursive 
computeIfAbsent calls
+    // preventing deadlock from occurring when a loading function mutates the 
underlying cache
+    org.cache2k.Cache<Object, Object> cache =
+        Cache2kBuilder.forUnknownTypes()
+            .maximumWeight(
+                options.as(SdkHarnessOptions.class).getMaxCacheMemoryUsageMb() 
* 1024L * 1024L)
+            .weigher(
+                new Weigher<Object, Object>() {
+                  private final MemoryMeter memoryMeter = 
MemoryMeter.builder().build();
+
+                  @Override
+                  public int weigh(Object key, Object value) {
+                    long size = memoryMeter.measureDeep(key) + 
memoryMeter.measureDeep(value);
+                    return size > Integer.MAX_VALUE ? Integer.MAX_VALUE : 
(int) size;
+                  }
+                })
+            .storeByReference(true)
+            .executor(MoreExecutors.directExecutor())
+            .build();
+
+    return (Cache<K, V>) forCache(cache);
+  }
+
+  /**
+   * Returns a view of a cache that operates on keys with a specified key 
prefix.
+   *
+   * <p>All lookups, insertions, and removals into the parent {@link Cache} 
will be prefixed by the
+   * specified prefixes.
+   *
+   * <p>Operations which operate over the entire caches contents such as 
{@link Cache#clear} only
+   * operate over keys with the specified prefixes.
+   */
+  public static <K, V> Cache<K, V> subCache(
+      Cache<?, ?> cache, Object keyPrefix, Object... additionalKeyPrefix) {
+    if (cache instanceof SubCache) {
+      return new SubCache<>(
+          ((SubCache<?, ?>) cache).cache,
+          ((SubCache<?, ?>) cache).keyPrefix.subKey(keyPrefix, 
additionalKeyPrefix));
+    } else if (cache instanceof SubCacheable) {
+      return new SubCache<>((SubCacheable<?, ?>) cache, 
CompositeKey.ROOT.subKey(keyPrefix));
+    }
+    throw new UnsupportedOperationException("An unsupported type of cache was 
passed.");
+  }
+
+  /** A cache that never evicts any values. */
+  public static <K, V> Cache<K, V> eternal() {
+    // We specifically use cache2k since it allows for recursive 
computeIfAbsent calls

Review comment:
       I assume this issue been known to happen with the Guava cache 
implementation?

##########
File path: 
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/Caches.java
##########
@@ -0,0 +1,285 @@
+/*
+ * 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.fn.harness;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Objects;
+import java.util.Set;
+import java.util.function.Function;
+import org.apache.beam.sdk.options.PipelineOptions;
+import org.apache.beam.sdk.options.SdkHarnessOptions;
+import 
org.apache.beam.vendor.guava.v26_0_jre.com.google.common.annotations.VisibleForTesting;
+import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.Sets;
+import 
org.apache.beam.vendor.guava.v26_0_jre.com.google.common.util.concurrent.MoreExecutors;
+import org.cache2k.Cache2kBuilder;
+import org.cache2k.operation.Weigher;
+import org.github.jamm.MemoryMeter;
+
+/** Utility methods used to instantiate and operate over cache instances. */
+@SuppressWarnings("nullness")
+public final class Caches {
+
+  /** A cache that never stores any values. */
+  public static <K, V> Cache<K, V> noop() {
+    return new SubCacheable<K, V>() {
+      @Override
+      public V peek(K key) {
+        return null;
+      }
+
+      @Override
+      public V computeIfAbsent(K key, Function<K, V> loadingFunction) {
+        return loadingFunction.apply(key);
+      }
+
+      @Override
+      public void put(K key, V value) {}
+
+      @Override
+      public void clear() {}
+
+      @Override
+      public void remove(K key) {}
+
+      @Override
+      public Set<K> keys() {
+        return Collections.emptySet();
+      }
+    };
+  }
+
+  /**
+   * Uses the specified {@link PipelineOptions} to configure and return a 
cache instance based upon
+   * parameters within {@link SdkHarnessOptions}.
+   */
+  public static <K, V> Cache<K, V> fromOptions(PipelineOptions options) {
+    // We specifically use cache2k since it allows for recursive 
computeIfAbsent calls
+    // preventing deadlock from occurring when a loading function mutates the 
underlying cache
+    org.cache2k.Cache<Object, Object> cache =
+        Cache2kBuilder.forUnknownTypes()
+            .maximumWeight(
+                options.as(SdkHarnessOptions.class).getMaxCacheMemoryUsageMb() 
* 1024L * 1024L)
+            .weigher(
+                new Weigher<Object, Object>() {
+                  private final MemoryMeter memoryMeter = 
MemoryMeter.builder().build();
+
+                  @Override
+                  public int weigh(Object key, Object value) {
+                    long size = memoryMeter.measureDeep(key) + 
memoryMeter.measureDeep(value);
+                    return size > Integer.MAX_VALUE ? Integer.MAX_VALUE : 
(int) size;
+                  }
+                })
+            .storeByReference(true)
+            .executor(MoreExecutors.directExecutor())
+            .build();
+
+    return (Cache<K, V>) forCache(cache);
+  }
+
+  /**
+   * Returns a view of a cache that operates on keys with a specified key 
prefix.
+   *
+   * <p>All lookups, insertions, and removals into the parent {@link Cache} 
will be prefixed by the
+   * specified prefixes.
+   *
+   * <p>Operations which operate over the entire caches contents such as 
{@link Cache#clear} only
+   * operate over keys with the specified prefixes.
+   */
+  public static <K, V> Cache<K, V> subCache(
+      Cache<?, ?> cache, Object keyPrefix, Object... additionalKeyPrefix) {
+    if (cache instanceof SubCache) {
+      return new SubCache<>(
+          ((SubCache<?, ?>) cache).cache,
+          ((SubCache<?, ?>) cache).keyPrefix.subKey(keyPrefix, 
additionalKeyPrefix));
+    } else if (cache instanceof SubCacheable) {
+      return new SubCache<>((SubCacheable<?, ?>) cache, 
CompositeKey.ROOT.subKey(keyPrefix));
+    }
+    throw new UnsupportedOperationException("An unsupported type of cache was 
passed.");

Review comment:
       Let's include the name of the unsupported type in the error message.

##########
File path: 
sdks/java/harness/src/test/java/org/apache/beam/fn/harness/CachesTest.java
##########
@@ -0,0 +1,105 @@
+/*
+ * 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.fn.harness;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
+import org.apache.beam.sdk.options.PipelineOptionsFactory;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/** Tests for {@link Caches}. */
+@RunWith(JUnit4.class)
+public class CachesTest {
+  @Test
+  public void testNoopCache() {
+    Cache<String, String> cache = Caches.noop();
+    cache.put("key", "value");
+    assertNull(cache.peek("key"));
+    assertEquals("value", cache.computeIfAbsent("key", (unused) -> "value"));
+    assertNull(cache.peek("key"));
+  }
+
+  @Test
+  public void testEternalCache() {
+    testCache(Caches.eternal());
+  }
+
+  @Test
+  public void testDefaultCache() {
+    testCache(Caches.fromOptions(PipelineOptionsFactory.create()));
+  }
+
+  @Test
+  public void testSubCache() {

Review comment:
       Can we test nested subcaches as well?




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