[ 
https://issues.apache.org/jira/browse/BEAM-4018?focusedWorklogId=94574&page=com.atlassian.jira.plugin.system.issuetabpanels:worklog-tabpanel#worklog-94574
 ]

ASF GitHub Bot logged work on BEAM-4018:
----------------------------------------

                Author: ASF GitHub Bot
            Created on: 24/Apr/18 12:04
            Start Date: 24/Apr/18 12:04
    Worklog Time Spent: 10m 
      Work Description: iemejia closed pull request #5175: [BEAM-4018] Add a 
ByteKeyRangeTracker based on RestrictionTracker for SDF
URL: https://github.com/apache/beam/pull/5175
 
 
   

This is a PR merged from a forked repository.
As GitHub hides the original diff on merge, it is displayed below for
the sake of provenance:

As this is a foreign pull request (from a fork), the diff is supplied
below (as it won't show otherwise due to GitHub magic):

diff --git 
a/sdks/java/core/src/main/java/org/apache/beam/sdk/io/range/ByteKeyRange.java 
b/sdks/java/core/src/main/java/org/apache/beam/sdk/io/range/ByteKeyRange.java
index d5b29198546..d13f1bcfa8a 100644
--- 
a/sdks/java/core/src/main/java/org/apache/beam/sdk/io/range/ByteKeyRange.java
+++ 
b/sdks/java/core/src/main/java/org/apache/beam/sdk/io/range/ByteKeyRange.java
@@ -283,7 +283,11 @@ public ByteKeyRange withEndKey(ByteKey endKey) {
   private ByteKeyRange(ByteKey startKey, ByteKey endKey) {
     this.startKey = checkNotNull(startKey, "startKey");
     this.endKey = checkNotNull(endKey, "endKey");
-    checkArgument(endsAfterKey(startKey), "Start %s must be less than end %s", 
startKey, endKey);
+    checkArgument(
+        endKey.isEmpty() || startKey.compareTo(endKey) <= 0,
+        "Start %s must be less than or equal to end %s",
+        startKey,
+        endKey);
   }
 
   @Override
diff --git 
a/sdks/java/core/src/main/java/org/apache/beam/sdk/transforms/splittabledofn/ByteKeyRangeTracker.java
 
b/sdks/java/core/src/main/java/org/apache/beam/sdk/transforms/splittabledofn/ByteKeyRangeTracker.java
new file mode 100644
index 00000000000..bee175ec261
--- /dev/null
+++ 
b/sdks/java/core/src/main/java/org/apache/beam/sdk/transforms/splittabledofn/ByteKeyRangeTracker.java
@@ -0,0 +1,158 @@
+/*
+ * 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.transforms.splittabledofn;
+
+import static com.google.common.base.Preconditions.checkArgument;
+import static com.google.common.base.Preconditions.checkNotNull;
+import static com.google.common.base.Preconditions.checkState;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.MoreObjects;
+import java.util.Arrays;
+import javax.annotation.Nullable;
+import org.apache.beam.sdk.io.range.ByteKey;
+import org.apache.beam.sdk.io.range.ByteKeyRange;
+import org.apache.beam.sdk.transforms.DoFn;
+
+/**
+ * A {@link RestrictionTracker} for claiming {@link ByteKey}s in a {@link 
ByteKeyRange} in a
+ * monotonically increasing fashion. The range is a semi-open bounded interval 
[startKey, endKey)
+ * where the limits are both represented by ByteKey.EMPTY.
+ */
+public class ByteKeyRangeTracker extends RestrictionTracker<ByteKeyRange, 
ByteKey> {
+  private ByteKeyRange range;
+  @Nullable private ByteKey lastClaimedKey = null;
+  @Nullable private ByteKey lastAttemptedKey = null;
+
+  private ByteKeyRangeTracker(ByteKeyRange range) {
+    this.range = checkNotNull(range);
+  }
+
+  public static ByteKeyRangeTracker of(ByteKeyRange range) {
+    return new ByteKeyRangeTracker(ByteKeyRange.of(range.getStartKey(), 
range.getEndKey()));
+  }
+
+  @Override
+  public synchronized ByteKeyRange currentRestriction() {
+    return range;
+  }
+
+  @Override
+  public synchronized ByteKeyRange checkpoint() {
+    checkState(lastClaimedKey != null, "Can't checkpoint before any key was 
successfully claimed");
+    ByteKey nextKey = next(lastClaimedKey);
+    ByteKeyRange res = ByteKeyRange.of(nextKey, range.getEndKey());
+    this.range = ByteKeyRange.of(range.getStartKey(), nextKey);
+    return res;
+  }
+
+  /**
+   * Attempts to claim the given key.
+   *
+   * <p>Must be larger than the last successfully claimed key.
+   *
+   * @return {@code true} if the key was successfully claimed, {@code false} 
if it is outside the
+   *     current {@link ByteKeyRange} of this tracker (in that case this 
operation is a no-op).
+   */
+  @Override
+  protected synchronized boolean tryClaimImpl(ByteKey key) {
+    checkArgument(
+        lastAttemptedKey == null || key.compareTo(lastAttemptedKey) > 0,
+        "Trying to claim key %s while last attempted was %s",
+        key,
+        lastAttemptedKey);
+    checkArgument(
+        key.compareTo(range.getStartKey()) > -1,
+        "Trying to claim key %s before start of the range %s",
+        key,
+        range);
+    lastAttemptedKey = key;
+    // No respective checkArgument for i < range.to() - it's ok to try 
claiming keys beyond
+    if (!range.getEndKey().isEmpty() && key.compareTo(range.getEndKey()) > -1) 
{
+      return false;
+    }
+    lastClaimedKey = key;
+    return true;
+  }
+
+  /**
+   * Marks that there are no more keys to be claimed in the range.
+   *
+   * <p>E.g., a {@link DoFn} reading a file and claiming the key of each 
record in the file might
+   * call this if it hits EOF - even though the last attempted claim was 
before the end of the
+   * range, there are no more keys to claim.
+   */
+  public synchronized void markDone() {
+    lastAttemptedKey = range.getEndKey();
+  }
+
+  @Override
+  public synchronized void checkDone() throws IllegalStateException {
+    checkState(lastAttemptedKey != null, "Can't check if done before any key 
claim was attempted");
+    ByteKey nextKey = next(lastAttemptedKey);
+    checkState(
+        nextKey.compareTo(range.getEndKey()) > -1,
+        "Last attempted key was %s in range %s, claiming work in [%s, %s) was 
not attempted",
+        lastAttemptedKey,
+        range,
+        nextKey,
+        range.getEndKey());
+  }
+
+  @Override
+  public String toString() {
+    return MoreObjects.toStringHelper(this)
+        .add("range", range)
+        .add("lastClaimedKey", lastClaimedKey)
+        .add("lastAttemptedKey", lastAttemptedKey)
+        .toString();
+  }
+
+  // Utility methods
+  /**
+   * Calculates the next {@link ByteKey} for a given key by incrementing by 
one using byte
+   * arithmetic. If the input key is empty it assumes it is a lower bound and 
returns the 00 byte
+   * array.
+   */
+  @VisibleForTesting
+  static ByteKey next(ByteKey key) {
+    return ByteKey.copyFrom(unsignedCopyAndIncrement(key.getBytes()));
+  }
+
+  /**
+   * @return The value of the input incremented by one using byte arithmetic. 
It treats the input
+   *     byte[] as an unsigned series of bytes, most significant bits first.
+   */
+  private static byte[] unsignedCopyAndIncrement(byte[] input) {
+    if (input.length == 0) {
+      return new byte[] {0};
+    }
+    byte[] copy = Arrays.copyOf(input, input.length);
+    for (int i = copy.length - 1; i >= 0; --i) {
+      if (copy[i] != (byte) 0xff) {
+        ++copy[i];
+        return copy;
+      }
+      copy[i] = 0;
+    }
+    byte[] out = new byte[copy.length + 1];
+    out[0] = 1;
+    System.arraycopy(copy, 0, out, 1, copy.length);
+    return out;
+  }
+}
diff --git 
a/sdks/java/core/src/test/java/org/apache/beam/sdk/io/range/ByteKeyRangeTest.java
 
b/sdks/java/core/src/test/java/org/apache/beam/sdk/io/range/ByteKeyRangeTest.java
index dd5597097dc..714d62962db 100644
--- 
a/sdks/java/core/src/test/java/org/apache/beam/sdk/io/range/ByteKeyRangeTest.java
+++ 
b/sdks/java/core/src/test/java/org/apache/beam/sdk/io/range/ByteKeyRangeTest.java
@@ -336,7 +336,7 @@ public void testRejectsInvalidRanges() {
     ByteKey[] testKeys = ByteKeyTest.TEST_KEYS;
     for (int i = 0; i < testKeys.length; ++i) {
       for (int j = i; j < testKeys.length; ++j) {
-        if (testKeys[i].isEmpty() || testKeys[j].isEmpty()) {
+        if (testKeys[i].isEmpty() || testKeys[j].isEmpty() || 
testKeys[j].equals(testKeys[i])) {
           continue; // these are valid ranges.
         }
         try {
diff --git 
a/sdks/java/core/src/test/java/org/apache/beam/sdk/transforms/splittabledofn/ByteKeyRangeTrackerTest.java
 
b/sdks/java/core/src/test/java/org/apache/beam/sdk/transforms/splittabledofn/ByteKeyRangeTrackerTest.java
new file mode 100644
index 00000000000..66e54a14268
--- /dev/null
+++ 
b/sdks/java/core/src/test/java/org/apache/beam/sdk/transforms/splittabledofn/ByteKeyRangeTrackerTest.java
@@ -0,0 +1,204 @@
+/*
+ * 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.transforms.splittabledofn;
+
+import static 
org.apache.beam.sdk.transforms.splittabledofn.ByteKeyRangeTracker.next;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import org.apache.beam.sdk.io.range.ByteKey;
+import org.apache.beam.sdk.io.range.ByteKeyRange;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/** Tests for {@link ByteKeyRangeTrackerTest}. */
+@RunWith(JUnit4.class)
+public class ByteKeyRangeTrackerTest {
+  @Rule public final ExpectedException expected = ExpectedException.none();
+
+  @Test
+  public void testTryClaim() throws Exception {
+    ByteKeyRange range = ByteKeyRange.of(ByteKey.of(0x10), ByteKey.of(0xc0));
+    ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(range);
+    assertEquals(range, tracker.currentRestriction());
+    assertTrue(tracker.tryClaim(ByteKey.of(0x10)));
+    assertTrue(tracker.tryClaim(ByteKey.of(0x10, 0x00)));
+    assertTrue(tracker.tryClaim(ByteKey.of(0x10, 0x00, 0x00)));
+    assertTrue(tracker.tryClaim(ByteKey.of(0x50)));
+    assertTrue(tracker.tryClaim(ByteKey.of(0x99)));
+    assertFalse(tracker.tryClaim(ByteKey.of(0xc0)));
+  }
+
+  @Test
+  public void testCheckpointUnstarted() throws Exception {
+    ByteKeyRangeTracker tracker =
+        ByteKeyRangeTracker.of(ByteKeyRange.of(ByteKey.of(0x10), 
ByteKey.of(0xc0)));
+    expected.expect(IllegalStateException.class);
+    tracker.checkpoint();
+  }
+
+  @Test
+  public void testCheckpointOnlyFailedClaim() throws Exception {
+    ByteKeyRangeTracker tracker =
+        ByteKeyRangeTracker.of(ByteKeyRange.of(ByteKey.of(0x10), 
ByteKey.of(0xc0)));
+    assertFalse(tracker.tryClaim(ByteKey.of(0xd0)));
+    expected.expect(IllegalStateException.class);
+    tracker.checkpoint();
+  }
+
+  @Test
+  public void testCheckpointJustStarted() throws Exception {
+    ByteKeyRangeTracker tracker =
+        ByteKeyRangeTracker.of(ByteKeyRange.of(ByteKey.of(0x10), 
ByteKey.of(0xc0)));
+    assertTrue(tracker.tryClaim(ByteKey.of(0x10)));
+    ByteKeyRange checkpoint = tracker.checkpoint();
+    assertEquals(ByteKeyRange.of(ByteKey.of(0x10), ByteKey.of(0x11)), 
tracker.currentRestriction());
+    assertEquals(ByteKeyRange.of(ByteKey.of(0x11), ByteKey.of(0xc0)), 
checkpoint);
+  }
+
+  @Test
+  public void testCheckpointRegular() throws Exception {
+    ByteKeyRangeTracker tracker =
+        ByteKeyRangeTracker.of(ByteKeyRange.of(ByteKey.of(0x10), 
ByteKey.of(0xc0)));
+    assertTrue(tracker.tryClaim(ByteKey.of(0x50)));
+    assertTrue(tracker.tryClaim(ByteKey.of(0x90)));
+    ByteKeyRange checkpoint = tracker.checkpoint();
+    assertEquals(ByteKeyRange.of(ByteKey.of(0x10), ByteKey.of(0x91)), 
tracker.currentRestriction());
+    assertEquals(ByteKeyRange.of(ByteKey.of(0x91), ByteKey.of(0xc0)), 
checkpoint);
+  }
+
+  @Test
+  public void testCheckpointClaimedLast() throws Exception {
+    ByteKeyRangeTracker tracker =
+        ByteKeyRangeTracker.of(ByteKeyRange.of(ByteKey.of(0x10), 
ByteKey.of(0xc0)));
+    assertTrue(tracker.tryClaim(ByteKey.of(0x50)));
+    assertTrue(tracker.tryClaim(ByteKey.of(0x90)));
+    assertTrue(tracker.tryClaim(ByteKey.of(0xbf)));
+    ByteKeyRange checkpoint = tracker.checkpoint();
+    assertEquals(ByteKeyRange.of(ByteKey.of(0x10), ByteKey.of(0xc0)), 
tracker.currentRestriction());
+    assertEquals(ByteKeyRange.of(ByteKey.of(0xc0), ByteKey.of(0xc0)), 
checkpoint);
+  }
+
+  @Test
+  public void testCheckpointAfterFailedClaim() throws Exception {
+    ByteKeyRangeTracker tracker =
+        ByteKeyRangeTracker.of(ByteKeyRange.of(ByteKey.of(0x10), 
ByteKey.of(0xc0)));
+    assertTrue(tracker.tryClaim(ByteKey.of(0x50)));
+    assertTrue(tracker.tryClaim(ByteKey.of(0x90)));
+    assertTrue(tracker.tryClaim(ByteKey.of(0xa0)));
+    assertFalse(tracker.tryClaim(ByteKey.of(0xd0)));
+    ByteKeyRange checkpoint = tracker.checkpoint();
+    assertEquals(ByteKeyRange.of(ByteKey.of(0x10), ByteKey.of(0xa1)), 
tracker.currentRestriction());
+    assertEquals(ByteKeyRange.of(ByteKey.of(0xa1), ByteKey.of(0xc0)), 
checkpoint);
+  }
+
+  @Test
+  public void testNonMonotonicClaim() throws Exception {
+    expected.expectMessage("Trying to claim key [70] while last attempted was 
[90]");
+    ByteKeyRangeTracker tracker =
+        ByteKeyRangeTracker.of(ByteKeyRange.of(ByteKey.of(0x10), 
ByteKey.of(0xc0)));
+    assertTrue(tracker.tryClaim(ByteKey.of(0x50)));
+    assertTrue(tracker.tryClaim(ByteKey.of(0x90)));
+    tracker.tryClaim(ByteKey.of(0x70));
+  }
+
+  @Test
+  public void testClaimBeforeStartOfRange() throws Exception {
+    expected.expectMessage(
+        "Trying to claim key [05] before start of the range "
+            + "ByteKeyRange{startKey=[10], endKey=[c0]}");
+    ByteKeyRangeTracker tracker =
+        ByteKeyRangeTracker.of(ByteKeyRange.of(ByteKey.of(0x10), 
ByteKey.of(0xc0)));
+    tracker.tryClaim(ByteKey.of(0x05));
+  }
+
+  @Test
+  public void testCheckDoneAfterTryClaimPastEndOfRange() {
+    ByteKeyRangeTracker tracker =
+        ByteKeyRangeTracker.of(ByteKeyRange.of(ByteKey.of(0x10), 
ByteKey.of(0xc0)));
+    assertTrue(tracker.tryClaim(ByteKey.of(0x50)));
+    assertTrue(tracker.tryClaim(ByteKey.of(0x90)));
+    assertFalse(tracker.tryClaim(ByteKey.of(0xd0)));
+    tracker.checkDone();
+  }
+
+  @Test
+  public void testCheckDoneAfterTryClaimAtEndOfRange() {
+    ByteKeyRangeTracker tracker =
+        ByteKeyRangeTracker.of(ByteKeyRange.of(ByteKey.of(0x10), 
ByteKey.of(0xc0)));
+    assertTrue(tracker.tryClaim(ByteKey.of(0x50)));
+    assertTrue(tracker.tryClaim(ByteKey.of(0x90)));
+    assertFalse(tracker.tryClaim(ByteKey.of(0xc0)));
+    tracker.checkDone();
+  }
+
+  @Test
+  public void testCheckDoneAfterTryClaimRightBeforeEndOfRange() {
+    ByteKeyRangeTracker tracker =
+        ByteKeyRangeTracker.of(ByteKeyRange.of(ByteKey.of(0x10), 
ByteKey.of(0xc0)));
+    assertTrue(tracker.tryClaim(ByteKey.of(0x50)));
+    assertTrue(tracker.tryClaim(ByteKey.of(0x90)));
+    assertTrue(tracker.tryClaim(ByteKey.of(0xbf)));
+    tracker.checkDone();
+  }
+
+  @Test
+  public void testCheckDoneWhenNotDone() {
+    ByteKeyRangeTracker tracker =
+        ByteKeyRangeTracker.of(ByteKeyRange.of(ByteKey.of(0x10), 
ByteKey.of(0xc0)));
+    assertTrue(tracker.tryClaim(ByteKey.of(0x50)));
+    assertTrue(tracker.tryClaim(ByteKey.of(0x90)));
+    expected.expectMessage(
+        "Last attempted key was [90] in range ByteKeyRange{startKey=[10], 
endKey=[c0]}, "
+            + "claiming work in [[91], [c0]) was not attempted");
+    tracker.checkDone();
+  }
+
+  @Test
+  public void testCheckDoneWhenExplicitlyMarkedDone() {
+    ByteKeyRangeTracker tracker =
+        ByteKeyRangeTracker.of(ByteKeyRange.of(ByteKey.of(0x10), 
ByteKey.of(0xc0)));
+    assertTrue(tracker.tryClaim(ByteKey.of(0x50)));
+    assertTrue(tracker.tryClaim(ByteKey.of(0x90)));
+    tracker.markDone();
+    tracker.checkDone();
+  }
+
+  @Test
+  public void testCheckDoneUnstarted() {
+    ByteKeyRangeTracker tracker =
+            ByteKeyRangeTracker.of(ByteKeyRange.of(ByteKey.of(0x10), 
ByteKey.of(0xc0)));
+    expected.expect(IllegalStateException.class);
+    tracker.checkDone();
+  }
+
+  @Test
+  public void testNextByteKey() {
+    assertEquals(next(ByteKey.EMPTY), ByteKey.of(0x00));
+    assertEquals(next(ByteKey.of(0x00)), ByteKey.of(0x01));
+    assertEquals(next(ByteKey.of(0x9f)), ByteKey.of(0xa0));
+    assertEquals(next(ByteKey.of(0xff)), ByteKey.of(0x01, 0x00));
+    assertEquals(next(ByteKey.of(0x10, 0x10)), ByteKey.of(0x10, 0x11));
+    assertEquals(next(ByteKey.of(0x00, 0xff)), ByteKey.of(0x01, 0x00));
+    assertEquals(next(ByteKey.of(0xff, 0xff)), ByteKey.of(0x01, 0x00, 0x00));
+  }
+}


 

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
[email protected]


Issue Time Tracking
-------------------

    Worklog Id:     (was: 94574)
    Time Spent: 7h  (was: 6h 50m)

> Add a ByteKeyRangeTracker based on RestrictionTracker for SDF
> -------------------------------------------------------------
>
>                 Key: BEAM-4018
>                 URL: https://issues.apache.org/jira/browse/BEAM-4018
>             Project: Beam
>          Issue Type: New Feature
>          Components: sdk-java-core
>            Reporter: Ismaël Mejía
>            Assignee: Ismaël Mejía
>            Priority: Minor
>             Fix For: 2.5.0
>
>          Time Spent: 7h
>  Remaining Estimate: 0h
>
> We can have a RestrictionTracker for ByteKey ranges as part of the core sdk 
> so it can be reused by future SDF based IOs like Bigtable, HBase among others.



--
This message was sent by Atlassian JIRA
(v7.6.3#76005)

Reply via email to