sabbey37 commented on a change in pull request #6489: URL: https://github.com/apache/geode/pull/6489#discussion_r635333392
########## File path: geode-apis-compatible-with-redis/src/integrationTest/java/org/apache/geode/redis/internal/executor/sortedset/AbstractZAddIntegrationTest.java ########## @@ -0,0 +1,253 @@ +/* + * 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.geode.redis.internal.executor.sortedset; + +import static org.apache.geode.redis.RedisCommandArgumentsTestHelper.assertAtLeastNArgs; +import static org.apache.geode.redis.internal.RedisConstants.ERROR_INVALID_ZADD_OPTION_NX_XX; +import static org.apache.geode.redis.internal.RedisConstants.ERROR_NOT_A_VALID_FLOAT; +import static org.apache.geode.redis.internal.RedisConstants.ERROR_SYNTAX; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import org.assertj.core.api.Assertions; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import redis.clients.jedis.HostAndPort; +import redis.clients.jedis.JedisCluster; +import redis.clients.jedis.Protocol; +import redis.clients.jedis.params.ZAddParams; + +import org.apache.geode.redis.RedisIntegrationTest; +import org.apache.geode.test.awaitility.GeodeAwaitility; + +public abstract class AbstractZAddIntegrationTest implements RedisIntegrationTest { + private JedisCluster jedis; + private static final int REDIS_CLIENT_TIMEOUT = + Math.toIntExact(GeodeAwaitility.getTimeout().toMillis()); + private static final String SORTED_SET_KEY = "ss_key"; + private static final int INITIAL_MEMBER_COUNT = 5; + + @Before + public void setUp() { + jedis = new JedisCluster(new HostAndPort("localhost", getPort()), REDIS_CLIENT_TIMEOUT); + } + + @After + public void tearDown() { + flushAll(); + jedis.close(); + } + + @Test + public void zaddErrors_givenTooFewArguments() { + assertAtLeastNArgs(jedis, Protocol.Command.ZADD, 3); + } + + @Test + public void zaddErrors_givenUnevenPairsOfArguments() { + assertThatThrownBy( + () -> jedis.sendCommand("fakeKey", Protocol.Command.ZADD, "fakeKey", "1", "member", "2")) + .hasMessageContaining("ERR syntax error"); + } + + @Test + public void zaddErrors_givenNonNumericScore() { + assertThatThrownBy( + () -> jedis.sendCommand("fakeKey", Protocol.Command.ZADD, "fakeKey", "xlerb", "member")) + .hasMessageContaining(ERROR_NOT_A_VALID_FLOAT); + } + + @Test + public void zaddErrors_givenBothNXAndXXOptions() { + assertThatThrownBy( + () -> jedis.sendCommand("fakeKey", Protocol.Command.ZADD, "fakeKey", "NX", "XX", "1.0", + "fakeMember")) + .hasMessageContaining(ERROR_INVALID_ZADD_OPTION_NX_XX); + } + + @Test + public void zaddErrors_givenBothNXAndGTOptions() { + assertThatThrownBy( + () -> jedis.sendCommand("fakeKey", Protocol.Command.ZADD, "fakeKey", "NX", "GT", "1.0", + "fakeMember")) + .hasMessageContaining(ERROR_SYNTAX); + } + + @Test + public void zaddErrors_givenBothNXAndLTOptions() { + assertThatThrownBy( + () -> jedis.sendCommand("fakeKey", Protocol.Command.ZADD, "fakeKey", "NX", "GT", "1.0", + "fakeMember")) + .hasMessageContaining(ERROR_SYNTAX); + } Review comment: The test says `zaddErrors_givenBothNXAndLTOptions`, but we pass in the `GT` option.... ########## File path: geode-apis-compatible-with-redis/src/integrationTest/java/org/apache/geode/redis/internal/executor/sortedset/AbstractZScoreIntegrationTest.java ########## @@ -0,0 +1,67 @@ +/* + * 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.geode.redis.internal.executor.sortedset; + +import static org.apache.geode.redis.RedisCommandArgumentsTestHelper.assertAtLeastNArgs; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import redis.clients.jedis.HostAndPort; +import redis.clients.jedis.JedisCluster; +import redis.clients.jedis.Protocol; + +import org.apache.geode.redis.RedisIntegrationTest; +import org.apache.geode.test.awaitility.GeodeAwaitility; + +public abstract class AbstractZScoreIntegrationTest implements RedisIntegrationTest { + private JedisCluster jedis; + private static final int REDIS_CLIENT_TIMEOUT = + Math.toIntExact(GeodeAwaitility.getTimeout().toMillis()); + + @Before + public void setUp() { + jedis = new JedisCluster(new HostAndPort("localhost", getPort()), REDIS_CLIENT_TIMEOUT); + } + + @After + public void tearDown() { + flushAll(); + jedis.close(); + } + + @Test + public void zscoreErrors_givenTooFewArguments() { + assertAtLeastNArgs(jedis, Protocol.Command.ZSCORE, 2); + } Review comment: We should also add a test for too many arguments and `WRONGTYPE` ########## File path: geode-apis-compatible-with-redis/src/main/java/org/apache/geode/redis/internal/RedisConstants.java ########## @@ -56,4 +56,8 @@ "Unknown subcommand or wrong number of arguments for '%s'. Try SLOWLOG HELP."; public static final String ERROR_UNKNOWN_CLUSTER_SUBCOMMAND = "Unknown subcommand or wrong number of arguments for '%s'. Try CLUSTER HELP."; + public static final String ERROR_INVALID_ZADD_OPTION_NX_XX = + "XX and NX options at the same time are not compatible"; + public static final String ERROR_INVALID_ZADD_OPTION_GT_LT_NX = + "GT, LT, and/or NX options at the same time are not compatible"; Review comment: This constant is unused and can be deleted. This error message is not present in Redis 5.x. Looks like it was added in 6.2. ########## File path: geode-apis-compatible-with-redis/src/main/java/org/apache/geode/redis/internal/ParameterRequirements/ZAddParameterRequirements.java ########## @@ -0,0 +1,116 @@ +/* + * 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.geode.redis.internal.ParameterRequirements; + +import static org.apache.geode.redis.internal.RedisConstants.ERROR_INVALID_ZADD_OPTION_NX_XX; +import static org.apache.geode.redis.internal.RedisConstants.ERROR_NOT_A_VALID_FLOAT; +import static org.apache.geode.redis.internal.RedisConstants.ERROR_SYNTAX; + +import java.util.Iterator; +import java.util.List; + +import org.apache.geode.redis.internal.netty.Coder; +import org.apache.geode.redis.internal.netty.Command; +import org.apache.geode.redis.internal.netty.ExecutionHandlerContext; + +public class ZAddParameterRequirements implements ParameterRequirements { + @Override + public void checkParameters(Command command, ExecutionHandlerContext context) { + int numberOfArguments = command.getProcessedCommand().size(); + + if (numberOfArguments < 4) { + throw new RedisParametersMismatchException(command.wrongNumberOfArgumentsErrorMessage()); + } + + int optionsFoundCount = confirmKnownSubcommands(command); + + if ((numberOfArguments - optionsFoundCount - 2) % 2 != 0) { + throw new RedisParametersMismatchException(ERROR_SYNTAX); + } + } + + private int confirmKnownSubcommands(Command command) { + int optionsFoundCount = 0; + boolean nxFound = false, xxFound = false, gtFound = false, ltFound = false; + + List<byte[]> commandElements = command.getProcessedCommand(); + Iterator<byte[]> commandIterator = commandElements.iterator(); + commandIterator.next(); // Skip past command + commandIterator.next(); // and key + + boolean scoreFound = false; + while (commandIterator.hasNext()) { + byte[] subcommand = commandIterator.next(); + String subCommandString = Coder.bytesToString(subcommand).toLowerCase(); + switch (subCommandString) { + case "ch": + break; + case "incr": + break; + case "nx": + nxFound = true; + break; + case "xx": + xxFound = true; + break; + case "gt": + gtFound = true; + if (nxFound) { + throw new RedisParametersMismatchException(String.format(ERROR_SYNTAX)); + } + break; + case "lt": + ltFound = true; + if (nxFound) { + throw new RedisParametersMismatchException(String.format(ERROR_SYNTAX)); + } Review comment: The error cases for `lt` and `gt` could be eliminated altogether, but the way we're detecting options will have to change.... the errors for `lt` and `gt` come from them not being available at all in Redis 5.x. .. they are treated the same as any other non-viable option. There are also some scenarios that would not work with our current implementation: one example is the following: `zadd key lt 1` returns `ERR value is not a valid float` in Redis (because it's trying to get the double value of `lt`), but we return `ERR syntax error`. ########## File path: geode-apis-compatible-with-redis/src/main/java/org/apache/geode/redis/internal/executor/sortedset/ZAddExecutor.java ########## @@ -0,0 +1,110 @@ +/* + * 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.geode.redis.internal.executor.sortedset; + + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.apache.geode.redis.internal.executor.RedisResponse; +import org.apache.geode.redis.internal.netty.Coder; +import org.apache.geode.redis.internal.netty.Command; +import org.apache.geode.redis.internal.netty.ExecutionHandlerContext; + +public class ZAddExecutor extends SortedSetExecutor { + @Override + public RedisResponse executeCommand(Command command, ExecutionHandlerContext context) { + RedisSortedSetCommands redisSortedSetCommands = createRedisSortedSetCommands(context); + + List<byte[]> commandElements = command.getProcessedCommand(); + + List<byte[]> scoresAndMembersToAdd = new ArrayList<>(); + Iterator<byte[]> commandIterator = commandElements.iterator(); + boolean adding = false; + boolean nxFound = false, xxFound = false, gtFound = false, ltFound = false; + int count = 0; + + while (commandIterator.hasNext()) { + byte[] next = commandIterator.next(); + if (count < 2) { // Skip past command, key + count++; + continue; + } else { + String subCommandString = Coder.bytesToString(next).toLowerCase(); + try { + Double.valueOf(subCommandString); + adding = true; + } catch (NumberFormatException nfe) { + switch (subCommandString) { + case "ch": + break; + case "incr": + break; + case "nx": + nxFound = true; + break; + case "xx": + xxFound = true; + break; + case "gt": + gtFound = true; + break; + case "lt": + ltFound = true; + break; + default: + // TODO: Should never happen? + } + } + } + if (adding) { + byte[] score = next; + scoresAndMembersToAdd.add(score); + if (commandIterator.hasNext()) { + byte[] member = commandIterator.next(); + scoresAndMembersToAdd.add(member); + } else { + // TODO: throw exception - should never happen + } + } + } + long entriesAdded = 0; + entriesAdded = redisSortedSetCommands.zadd(command.getKey(), scoresAndMembersToAdd, + makeOptions(nxFound, xxFound, gtFound, ltFound)); + + return RedisResponse.integer(entriesAdded); + } + + private SortedSetOptions makeOptions(boolean nxFound, boolean xxFound, boolean gtFound, + boolean ltFound) { + SortedSetOptions.Exists existsOption = SortedSetOptions.Exists.NONE; + SortedSetOptions.Update updateOption = SortedSetOptions.Update.NONE; + + if (nxFound) { + existsOption = SortedSetOptions.Exists.NX; + } + if (xxFound) { + existsOption = SortedSetOptions.Exists.XX; + } + if (gtFound) { + updateOption = SortedSetOptions.Update.GT; + } + if (ltFound) { + updateOption = SortedSetOptions.Update.LT; + } Review comment: Since these options were added in 6.2 and we're matching Redis 5.x, we can remove this code and all unneeded GT/LT -related code and add this functionality when we decide to update to Redis 6.x. ########## File path: geode-apis-compatible-with-redis/src/main/java/org/apache/geode/redis/internal/ParameterRequirements/ZAddParameterRequirements.java ########## @@ -0,0 +1,116 @@ +/* + * 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.geode.redis.internal.ParameterRequirements; + +import static org.apache.geode.redis.internal.RedisConstants.ERROR_INVALID_ZADD_OPTION_NX_XX; +import static org.apache.geode.redis.internal.RedisConstants.ERROR_NOT_A_VALID_FLOAT; +import static org.apache.geode.redis.internal.RedisConstants.ERROR_SYNTAX; + +import java.util.Iterator; +import java.util.List; + +import org.apache.geode.redis.internal.netty.Coder; +import org.apache.geode.redis.internal.netty.Command; +import org.apache.geode.redis.internal.netty.ExecutionHandlerContext; + +public class ZAddParameterRequirements implements ParameterRequirements { + @Override + public void checkParameters(Command command, ExecutionHandlerContext context) { + int numberOfArguments = command.getProcessedCommand().size(); + + if (numberOfArguments < 4) { + throw new RedisParametersMismatchException(command.wrongNumberOfArgumentsErrorMessage()); + } + + int optionsFoundCount = confirmKnownSubcommands(command); + + if ((numberOfArguments - optionsFoundCount - 2) % 2 != 0) { + throw new RedisParametersMismatchException(ERROR_SYNTAX); + } + } + + private int confirmKnownSubcommands(Command command) { + int optionsFoundCount = 0; + boolean nxFound = false, xxFound = false, gtFound = false, ltFound = false; + + List<byte[]> commandElements = command.getProcessedCommand(); + Iterator<byte[]> commandIterator = commandElements.iterator(); + commandIterator.next(); // Skip past command + commandIterator.next(); // and key + + boolean scoreFound = false; + while (commandIterator.hasNext()) { + byte[] subcommand = commandIterator.next(); + String subCommandString = Coder.bytesToString(subcommand).toLowerCase(); + switch (subCommandString) { + case "ch": + break; + case "incr": + break; + case "nx": + nxFound = true; + break; + case "xx": + xxFound = true; + break; + case "gt": + gtFound = true; + if (nxFound) { + throw new RedisParametersMismatchException(String.format(ERROR_SYNTAX)); + } + break; + case "lt": + ltFound = true; + if (nxFound) { + throw new RedisParametersMismatchException(String.format(ERROR_SYNTAX)); + } + break; + default: + try { + Double.valueOf(subCommandString); + scoreFound = true; + break; + } catch (NumberFormatException nfe) { + throw new RedisParametersMismatchException(String.format(ERROR_NOT_A_VALID_FLOAT)); + } + } + if (scoreFound) { + break; + } + optionsFoundCount++; + } + + validateFlagCombinations(nxFound, xxFound, gtFound, ltFound); + + return optionsFoundCount; + } + + private void validateFlagCombinations(boolean nxFound, boolean xxFound, boolean gtFound, + boolean ltFound) { + if (nxFound && xxFound) { + throw new RedisParametersMismatchException( + String.format(ERROR_INVALID_ZADD_OPTION_NX_XX)); + } + if (gtFound && ltFound) { + throw new RedisParametersMismatchException( + String.format(ERROR_NOT_A_VALID_FLOAT)); + } + if ((gtFound || ltFound) && nxFound) { + throw new RedisParametersMismatchException( + String.format(ERROR_NOT_A_VALID_FLOAT)); + } Review comment: The `String.format` here as well as some places above it is not needed since we're not adding a variable to the string. ########## File path: geode-apis-compatible-with-redis/src/main/java/org/apache/geode/redis/internal/ParameterRequirements/ZAddParameterRequirements.java ########## @@ -0,0 +1,116 @@ +/* + * 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.geode.redis.internal.ParameterRequirements; + +import static org.apache.geode.redis.internal.RedisConstants.ERROR_INVALID_ZADD_OPTION_NX_XX; +import static org.apache.geode.redis.internal.RedisConstants.ERROR_NOT_A_VALID_FLOAT; +import static org.apache.geode.redis.internal.RedisConstants.ERROR_SYNTAX; + +import java.util.Iterator; +import java.util.List; + +import org.apache.geode.redis.internal.netty.Coder; +import org.apache.geode.redis.internal.netty.Command; +import org.apache.geode.redis.internal.netty.ExecutionHandlerContext; + +public class ZAddParameterRequirements implements ParameterRequirements { + @Override + public void checkParameters(Command command, ExecutionHandlerContext context) { + int numberOfArguments = command.getProcessedCommand().size(); + + if (numberOfArguments < 4) { + throw new RedisParametersMismatchException(command.wrongNumberOfArgumentsErrorMessage()); + } Review comment: Since we support adding multiple `ParameterRequirements` in `RedisCommandType`, we could remove this here and add the `MinimumParameterRequirements` to `ZADD` in command type so we avoid duplicating this code: ``` ZADD(new ZAddExecutor(), SUPPORTED, new ZAddParameterRequirements().and(new MinimumParameterRequirements(4))), ``` ########## File path: geode-apis-compatible-with-redis/src/integrationTest/java/org/apache/geode/redis/internal/executor/sortedset/AbstractZAddIntegrationTest.java ########## @@ -0,0 +1,253 @@ +/* + * 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.geode.redis.internal.executor.sortedset; + +import static org.apache.geode.redis.RedisCommandArgumentsTestHelper.assertAtLeastNArgs; +import static org.apache.geode.redis.internal.RedisConstants.ERROR_INVALID_ZADD_OPTION_NX_XX; +import static org.apache.geode.redis.internal.RedisConstants.ERROR_NOT_A_VALID_FLOAT; +import static org.apache.geode.redis.internal.RedisConstants.ERROR_SYNTAX; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import org.assertj.core.api.Assertions; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import redis.clients.jedis.HostAndPort; +import redis.clients.jedis.JedisCluster; +import redis.clients.jedis.Protocol; +import redis.clients.jedis.params.ZAddParams; + +import org.apache.geode.redis.RedisIntegrationTest; +import org.apache.geode.test.awaitility.GeodeAwaitility; + +public abstract class AbstractZAddIntegrationTest implements RedisIntegrationTest { + private JedisCluster jedis; + private static final int REDIS_CLIENT_TIMEOUT = + Math.toIntExact(GeodeAwaitility.getTimeout().toMillis()); + private static final String SORTED_SET_KEY = "ss_key"; + private static final int INITIAL_MEMBER_COUNT = 5; + + @Before + public void setUp() { + jedis = new JedisCluster(new HostAndPort("localhost", getPort()), REDIS_CLIENT_TIMEOUT); + } + + @After + public void tearDown() { + flushAll(); + jedis.close(); + } + + @Test + public void zaddErrors_givenTooFewArguments() { + assertAtLeastNArgs(jedis, Protocol.Command.ZADD, 3); + } + + @Test + public void zaddErrors_givenUnevenPairsOfArguments() { + assertThatThrownBy( + () -> jedis.sendCommand("fakeKey", Protocol.Command.ZADD, "fakeKey", "1", "member", "2")) + .hasMessageContaining("ERR syntax error"); + } + + @Test + public void zaddErrors_givenNonNumericScore() { + assertThatThrownBy( + () -> jedis.sendCommand("fakeKey", Protocol.Command.ZADD, "fakeKey", "xlerb", "member")) + .hasMessageContaining(ERROR_NOT_A_VALID_FLOAT); + } + + @Test + public void zaddErrors_givenBothNXAndXXOptions() { + assertThatThrownBy( + () -> jedis.sendCommand("fakeKey", Protocol.Command.ZADD, "fakeKey", "NX", "XX", "1.0", + "fakeMember")) + .hasMessageContaining(ERROR_INVALID_ZADD_OPTION_NX_XX); + } + + @Test + public void zaddErrors_givenBothNXAndGTOptions() { + assertThatThrownBy( + () -> jedis.sendCommand("fakeKey", Protocol.Command.ZADD, "fakeKey", "NX", "GT", "1.0", + "fakeMember")) + .hasMessageContaining(ERROR_SYNTAX); + } + + @Test + public void zaddErrors_givenBothNXAndLTOptions() { + assertThatThrownBy( + () -> jedis.sendCommand("fakeKey", Protocol.Command.ZADD, "fakeKey", "NX", "GT", "1.0", + "fakeMember")) + .hasMessageContaining(ERROR_SYNTAX); + } + + @Test + public void zaddErrors_givenLTThenNXOptions() { + assertThatThrownBy( + () -> jedis.sendCommand("fakeKey", Protocol.Command.ZADD, "fakeKey", "LT", "NX", "1.0", + "fakeMember")) + .hasMessageContaining(ERROR_NOT_A_VALID_FLOAT); + } + + @Test + public void zaddErrors_givenGTThenNXOptions() { + assertThatThrownBy( + () -> jedis.sendCommand("fakeKey", Protocol.Command.ZADD, "fakeKey", "GT", "NX", "1.0", + "fakeMember")) + .hasMessageContaining(ERROR_NOT_A_VALID_FLOAT); + } + + @Test + public void zaddErrors_givenBothGTAndLTOptions() { + assertThatThrownBy( + () -> jedis.sendCommand("fakeKey", Protocol.Command.ZADD, "fakeKey", "LT", "GT", "1", + "fakeMember")) + .hasMessageContaining(ERROR_NOT_A_VALID_FLOAT); + } + Review comment: We should also add a check for the `WRONGTYPE` error when trying to do ZADD on a different data structure. ########## File path: geode-apis-compatible-with-redis/src/main/java/org/apache/geode/redis/internal/data/RedisSortedSet.java ########## @@ -0,0 +1,286 @@ +/* + * 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.geode.redis.internal.data; + +import static org.apache.geode.redis.internal.data.RedisDataType.REDIS_SORTED_SET; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import it.unimi.dsi.fastutil.bytes.ByteArrays; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenCustomHashMap; + +import org.apache.geode.cache.Region; +import org.apache.geode.internal.InternalDataSerializer; +import org.apache.geode.internal.serialization.DeserializationContext; +import org.apache.geode.internal.serialization.KnownVersion; +import org.apache.geode.internal.serialization.SerializationContext; +import org.apache.geode.redis.internal.delta.AddsDeltaInfo; +import org.apache.geode.redis.internal.delta.DeltaInfo; +import org.apache.geode.redis.internal.delta.RemsDeltaInfo; +import org.apache.geode.redis.internal.executor.sortedset.SortedSetOptions; + +public class RedisSortedSet extends AbstractRedisData { + private Object2ObjectOpenCustomHashMap<byte[], byte[]> members; + + protected static final int BASE_REDIS_SORTED_SET_OVERHEAD = 184; + protected static final int PER_PAIR_OVERHEAD = 48; + + private int sizeInBytes; + + @Override + public int getSizeInBytes() { + return sizeInBytes; + } + + private enum AddOrChange { + ADDED, CHANGED, NOOP + } + + private int calculateSizeOfNewFieldValuePair(byte[] member, byte[] score) { + return PER_PAIR_OVERHEAD + member.length + score.length; + } + + RedisSortedSet(List<byte[]> members) { + sizeInBytes += BASE_REDIS_SORTED_SET_OVERHEAD; + this.members = new Object2ObjectOpenCustomHashMap<>(members.size(), ByteArrays.HASH_STRATEGY); + Iterator<byte[]> iterator = members.iterator(); + + while (iterator.hasNext()) { + byte[] score = iterator.next(); + byte[] member = iterator.next(); + sizeInBytes += calculateSizeOfNewFieldValuePair(member, score); + this.members.put(member, score); + } + } + + RedisSortedSet(List<byte[]> members, SortedSetOptions options) { + if (options.isXX()) { + sizeInBytes += BASE_REDIS_SORTED_SET_OVERHEAD; + this.members = new Object2ObjectOpenCustomHashMap<>(members.size(), ByteArrays.HASH_STRATEGY); + } else { + RedisSortedSet tempSet = new RedisSortedSet(members); + this.members = tempSet.members; + this.sizeInBytes = tempSet.sizeInBytes; + } + } Review comment: I think we could do something like this instead to clean this up a bit (removing the addition of the overhead to `sizeInBytes` once the variable is initialized with that): ``` RedisSortedSet(List<byte[]> members) { this(members, new SortedSetOptions(SortedSetOptions.Exists.NONE, SortedSetOptions.Update.NONE)); } RedisSortedSet(List<byte[]> members, SortedSetOptions options) { if (!options.isXX()) { sizeInBytes += BASE_REDIS_SORTED_SET_OVERHEAD; this.members = new Object2ObjectOpenCustomHashMap<>(members.size(), ByteArrays.HASH_STRATEGY); Iterator<byte[]> iterator = members.iterator(); while (iterator.hasNext()) { byte[] score = iterator.next(); byte[] member = iterator.next(); sizeInBytes += calculateSizeOfNewFieldValuePair(member, score); this.members.put(member, score); } } } ``` ...we don't need to do anything if the option is XX and it's a new sorted set since it never gets added to the region at all. ########## File path: geode-apis-compatible-with-redis/src/integrationTest/java/org/apache/geode/redis/internal/executor/sortedset/AbstractZScoreIntegrationTest.java ########## @@ -0,0 +1,67 @@ +/* + * 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.geode.redis.internal.executor.sortedset; + +import static org.apache.geode.redis.RedisCommandArgumentsTestHelper.assertAtLeastNArgs; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import redis.clients.jedis.HostAndPort; +import redis.clients.jedis.JedisCluster; +import redis.clients.jedis.Protocol; + +import org.apache.geode.redis.RedisIntegrationTest; +import org.apache.geode.test.awaitility.GeodeAwaitility; + +public abstract class AbstractZScoreIntegrationTest implements RedisIntegrationTest { + private JedisCluster jedis; + private static final int REDIS_CLIENT_TIMEOUT = + Math.toIntExact(GeodeAwaitility.getTimeout().toMillis()); + + @Before + public void setUp() { + jedis = new JedisCluster(new HostAndPort("localhost", getPort()), REDIS_CLIENT_TIMEOUT); + } + + @After + public void tearDown() { + flushAll(); + jedis.close(); + } + + @Test + public void zscoreErrors_givenTooFewArguments() { + assertAtLeastNArgs(jedis, Protocol.Command.ZSCORE, 2); + } + + @Test + public void zscoreReturnsNil_givenNonexistentKey() { + assertThat(jedis.zscore("fakeKey", "fakeMember")).isEqualTo(null); + } + + @Test + public void zscoreReturnsNil_givenNonexistentMember() { + jedis.zadd("key", 1.0, "member"); + assertThat(jedis.zscore("fakeKey", "fakeMember")).isEqualTo(null); Review comment: Could we use `key` here instead of `fakeKey`, so we can check the `NonexistentMember`? ########## File path: geode-apis-compatible-with-redis/src/main/java/org/apache/geode/redis/internal/data/RedisSortedSet.java ########## @@ -0,0 +1,286 @@ +/* + * 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.geode.redis.internal.data; + +import static org.apache.geode.redis.internal.data.RedisDataType.REDIS_SORTED_SET; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import it.unimi.dsi.fastutil.bytes.ByteArrays; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenCustomHashMap; + +import org.apache.geode.cache.Region; +import org.apache.geode.internal.InternalDataSerializer; +import org.apache.geode.internal.serialization.DeserializationContext; +import org.apache.geode.internal.serialization.KnownVersion; +import org.apache.geode.internal.serialization.SerializationContext; +import org.apache.geode.redis.internal.delta.AddsDeltaInfo; +import org.apache.geode.redis.internal.delta.DeltaInfo; +import org.apache.geode.redis.internal.delta.RemsDeltaInfo; +import org.apache.geode.redis.internal.executor.sortedset.SortedSetOptions; + +public class RedisSortedSet extends AbstractRedisData { + private Object2ObjectOpenCustomHashMap<byte[], byte[]> members; + + protected static final int BASE_REDIS_SORTED_SET_OVERHEAD = 184; + protected static final int PER_PAIR_OVERHEAD = 48; + + private int sizeInBytes; + + @Override + public int getSizeInBytes() { + return sizeInBytes; + } + + private enum AddOrChange { + ADDED, CHANGED, NOOP + } + + private int calculateSizeOfNewFieldValuePair(byte[] member, byte[] score) { + return PER_PAIR_OVERHEAD + member.length + score.length; + } + + RedisSortedSet(List<byte[]> members) { + sizeInBytes += BASE_REDIS_SORTED_SET_OVERHEAD; + this.members = new Object2ObjectOpenCustomHashMap<>(members.size(), ByteArrays.HASH_STRATEGY); + Iterator<byte[]> iterator = members.iterator(); + + while (iterator.hasNext()) { + byte[] score = iterator.next(); + byte[] member = iterator.next(); + sizeInBytes += calculateSizeOfNewFieldValuePair(member, score); + this.members.put(member, score); + } + } + + RedisSortedSet(List<byte[]> members, SortedSetOptions options) { + if (options.isXX()) { + sizeInBytes += BASE_REDIS_SORTED_SET_OVERHEAD; + this.members = new Object2ObjectOpenCustomHashMap<>(members.size(), ByteArrays.HASH_STRATEGY); + } else { + RedisSortedSet tempSet = new RedisSortedSet(members); + this.members = tempSet.members; + this.sizeInBytes = tempSet.sizeInBytes; + } + } + + // for serialization + public RedisSortedSet() {} + + @Override + protected void applyDelta(DeltaInfo deltaInfo) { + if (deltaInfo instanceof AddsDeltaInfo) { + AddsDeltaInfo addsDeltaInfo = (AddsDeltaInfo) deltaInfo; + membersAddAll(addsDeltaInfo); + } else { + RemsDeltaInfo remsDeltaInfo = (RemsDeltaInfo) deltaInfo; + membersRemoveAll(remsDeltaInfo); + } + } + + /** + * Since GII (getInitialImage) can come in and call toData while other threads are modifying this + * object, the striped executor will not protect toData. So any methods that modify "members" + * needs to be thread safe with toData. + */ + + @Override + public synchronized void toData(DataOutput out, SerializationContext context) throws IOException { + super.toData(out, context); + InternalDataSerializer.writePrimitiveInt(members.size(), out); + for (Map.Entry<byte[], byte[]> entry : members.entrySet()) { + byte[] key = entry.getKey(); + byte[] value = entry.getValue(); + InternalDataSerializer.writeByteArray(key, out); + InternalDataSerializer.writeByteArray(value, out); + } + InternalDataSerializer.writePrimitiveInt(sizeInBytes, out); + } + + @Override + public void fromData(DataInput in, DeserializationContext context) + throws IOException, ClassNotFoundException { + super.fromData(in, context); + int size = InternalDataSerializer.readPrimitiveInt(in); + members = new Object2ObjectOpenCustomHashMap<>(size, ByteArrays.HASH_STRATEGY); + for (int i = 0; i < size; i++) { + members.put(InternalDataSerializer.readByteArray(in), + InternalDataSerializer.readByteArray(in)); + } + sizeInBytes = InternalDataSerializer.readPrimitiveInt(in); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof RedisSortedSet)) { + return false; + } + if (!super.equals(o)) { + return false; + } + RedisSortedSet redisSortedSet = (RedisSortedSet) o; + if (members.size() != redisSortedSet.members.size()) { + return false; + } + + for (Map.Entry<byte[], byte[]> entry : members.entrySet()) { + if (!Arrays.equals(redisSortedSet.members.get(entry.getKey()), (entry.getValue()))) { + return false; + } + } + return true; + } + + @Override + public int getDSFID() { + return REDIS_SORTED_SET_ID; + } + + protected synchronized AddOrChange memberAdd(byte[] memberToAdd, byte[] scoreToAdd) { + boolean added = (members.put(memberToAdd, scoreToAdd) == null); + if (added) { + sizeInBytes += calculateSizeOfNewFieldValuePair(memberToAdd, scoreToAdd); + } + return added ? AddOrChange.ADDED : AddOrChange.NOOP; + } + + private synchronized void membersAddAll(AddsDeltaInfo addsDeltaInfo) { + Iterator<byte[]> iterator = addsDeltaInfo.getAdds().iterator(); + while (iterator.hasNext()) { + byte[] member = iterator.next(); + sizeInBytes += PER_PAIR_OVERHEAD + member.length; + byte[] score = iterator.next(); + sizeInBytes += PER_PAIR_OVERHEAD + score.length; + members.put(member, score); Review comment: Not sure why we add the `PER_PAIR_OVERHEAD` for score and member when previous methods only added it once for both. Also, seems like we could reuse the `calculateSizeOfNewFieldValuePair` method. ########## File path: geode-apis-compatible-with-redis/src/main/java/org/apache/geode/redis/internal/executor/sortedset/ZAddExecutor.java ########## @@ -0,0 +1,110 @@ +/* + * 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.geode.redis.internal.executor.sortedset; + + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.apache.geode.redis.internal.executor.RedisResponse; +import org.apache.geode.redis.internal.netty.Coder; +import org.apache.geode.redis.internal.netty.Command; +import org.apache.geode.redis.internal.netty.ExecutionHandlerContext; + +public class ZAddExecutor extends SortedSetExecutor { + @Override + public RedisResponse executeCommand(Command command, ExecutionHandlerContext context) { + RedisSortedSetCommands redisSortedSetCommands = createRedisSortedSetCommands(context); + + List<byte[]> commandElements = command.getProcessedCommand(); + + List<byte[]> scoresAndMembersToAdd = new ArrayList<>(); + Iterator<byte[]> commandIterator = commandElements.iterator(); + boolean adding = false; + boolean nxFound = false, xxFound = false, gtFound = false, ltFound = false; + int count = 0; + + while (commandIterator.hasNext()) { + byte[] next = commandIterator.next(); + if (count < 2) { // Skip past command, key + count++; + continue; + } else { + String subCommandString = Coder.bytesToString(next).toLowerCase(); + try { + Double.valueOf(subCommandString); + adding = true; + } catch (NumberFormatException nfe) { + switch (subCommandString) { + case "ch": + break; + case "incr": + break; + case "nx": + nxFound = true; + break; + case "xx": + xxFound = true; + break; + case "gt": + gtFound = true; + break; + case "lt": + ltFound = true; + break; + default: + // TODO: Should never happen? + } + } + } + if (adding) { + byte[] score = next; + scoresAndMembersToAdd.add(score); + if (commandIterator.hasNext()) { + byte[] member = commandIterator.next(); + scoresAndMembersToAdd.add(member); + } else { + // TODO: throw exception - should never happen + } + } + } + long entriesAdded = 0; + entriesAdded = redisSortedSetCommands.zadd(command.getKey(), scoresAndMembersToAdd, + makeOptions(nxFound, xxFound, gtFound, ltFound)); Review comment: you don't need the extra assignment of `entriesAdded = 0` since `zadd` will return 0 if nothing was added. ########## File path: geode-apis-compatible-with-redis/src/main/java/org/apache/geode/redis/internal/data/RedisSortedSet.java ########## @@ -0,0 +1,286 @@ +/* + * 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.geode.redis.internal.data; + +import static org.apache.geode.redis.internal.data.RedisDataType.REDIS_SORTED_SET; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import it.unimi.dsi.fastutil.bytes.ByteArrays; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenCustomHashMap; + +import org.apache.geode.cache.Region; +import org.apache.geode.internal.InternalDataSerializer; +import org.apache.geode.internal.serialization.DeserializationContext; +import org.apache.geode.internal.serialization.KnownVersion; +import org.apache.geode.internal.serialization.SerializationContext; +import org.apache.geode.redis.internal.delta.AddsDeltaInfo; +import org.apache.geode.redis.internal.delta.DeltaInfo; +import org.apache.geode.redis.internal.delta.RemsDeltaInfo; +import org.apache.geode.redis.internal.executor.sortedset.SortedSetOptions; + +public class RedisSortedSet extends AbstractRedisData { + private Object2ObjectOpenCustomHashMap<byte[], byte[]> members; + + protected static final int BASE_REDIS_SORTED_SET_OVERHEAD = 184; + protected static final int PER_PAIR_OVERHEAD = 48; + + private int sizeInBytes; + + @Override + public int getSizeInBytes() { + return sizeInBytes; + } + + private enum AddOrChange { + ADDED, CHANGED, NOOP + } + + private int calculateSizeOfNewFieldValuePair(byte[] member, byte[] score) { + return PER_PAIR_OVERHEAD + member.length + score.length; + } + + RedisSortedSet(List<byte[]> members) { + sizeInBytes += BASE_REDIS_SORTED_SET_OVERHEAD; + this.members = new Object2ObjectOpenCustomHashMap<>(members.size(), ByteArrays.HASH_STRATEGY); + Iterator<byte[]> iterator = members.iterator(); + + while (iterator.hasNext()) { + byte[] score = iterator.next(); + byte[] member = iterator.next(); + sizeInBytes += calculateSizeOfNewFieldValuePair(member, score); + this.members.put(member, score); + } + } + + RedisSortedSet(List<byte[]> members, SortedSetOptions options) { + if (options.isXX()) { + sizeInBytes += BASE_REDIS_SORTED_SET_OVERHEAD; + this.members = new Object2ObjectOpenCustomHashMap<>(members.size(), ByteArrays.HASH_STRATEGY); + } else { + RedisSortedSet tempSet = new RedisSortedSet(members); + this.members = tempSet.members; + this.sizeInBytes = tempSet.sizeInBytes; + } + } + + // for serialization + public RedisSortedSet() {} + + @Override + protected void applyDelta(DeltaInfo deltaInfo) { + if (deltaInfo instanceof AddsDeltaInfo) { + AddsDeltaInfo addsDeltaInfo = (AddsDeltaInfo) deltaInfo; + membersAddAll(addsDeltaInfo); + } else { + RemsDeltaInfo remsDeltaInfo = (RemsDeltaInfo) deltaInfo; + membersRemoveAll(remsDeltaInfo); + } + } + + /** + * Since GII (getInitialImage) can come in and call toData while other threads are modifying this + * object, the striped executor will not protect toData. So any methods that modify "members" + * needs to be thread safe with toData. + */ + + @Override + public synchronized void toData(DataOutput out, SerializationContext context) throws IOException { + super.toData(out, context); + InternalDataSerializer.writePrimitiveInt(members.size(), out); + for (Map.Entry<byte[], byte[]> entry : members.entrySet()) { + byte[] key = entry.getKey(); + byte[] value = entry.getValue(); + InternalDataSerializer.writeByteArray(key, out); + InternalDataSerializer.writeByteArray(value, out); + } + InternalDataSerializer.writePrimitiveInt(sizeInBytes, out); + } + + @Override + public void fromData(DataInput in, DeserializationContext context) + throws IOException, ClassNotFoundException { + super.fromData(in, context); + int size = InternalDataSerializer.readPrimitiveInt(in); + members = new Object2ObjectOpenCustomHashMap<>(size, ByteArrays.HASH_STRATEGY); + for (int i = 0; i < size; i++) { + members.put(InternalDataSerializer.readByteArray(in), + InternalDataSerializer.readByteArray(in)); + } + sizeInBytes = InternalDataSerializer.readPrimitiveInt(in); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof RedisSortedSet)) { + return false; + } + if (!super.equals(o)) { + return false; + } + RedisSortedSet redisSortedSet = (RedisSortedSet) o; + if (members.size() != redisSortedSet.members.size()) { + return false; + } + + for (Map.Entry<byte[], byte[]> entry : members.entrySet()) { + if (!Arrays.equals(redisSortedSet.members.get(entry.getKey()), (entry.getValue()))) { + return false; + } + } + return true; + } + + @Override + public int getDSFID() { + return REDIS_SORTED_SET_ID; + } + + protected synchronized AddOrChange memberAdd(byte[] memberToAdd, byte[] scoreToAdd) { + boolean added = (members.put(memberToAdd, scoreToAdd) == null); + if (added) { + sizeInBytes += calculateSizeOfNewFieldValuePair(memberToAdd, scoreToAdd); + } + return added ? AddOrChange.ADDED : AddOrChange.NOOP; + } + + private synchronized void membersAddAll(AddsDeltaInfo addsDeltaInfo) { + Iterator<byte[]> iterator = addsDeltaInfo.getAdds().iterator(); + while (iterator.hasNext()) { + byte[] member = iterator.next(); + sizeInBytes += PER_PAIR_OVERHEAD + member.length; + byte[] score = iterator.next(); + sizeInBytes += PER_PAIR_OVERHEAD + score.length; + members.put(member, score); + } + } + + + private synchronized void membersRemoveAll(RemsDeltaInfo remsDeltaInfo) { + for (byte[] member : remsDeltaInfo.getRemoves()) { + sizeInBytes -= (PER_PAIR_OVERHEAD + member.length); + members.remove(member); + } + } + + /** + * @param region the region this instance is stored in + * @param key the name of the set to add to + * @param membersToAdd members to add to this set; NOTE this list may by modified by this call + * @return the number of members actually added + */ + long zadd(Region<RedisKey, RedisData> region, RedisKey key, List<byte[]> membersToAdd, + SortedSetOptions options) { + int membersAdded = 0; + if (options == null) { + options = new SortedSetOptions(SortedSetOptions.Exists.NONE, SortedSetOptions.Update.NONE); + } + AddsDeltaInfo deltaInfo = null; + Iterator<byte[]> iterator = membersToAdd.iterator(); + while (iterator.hasNext()) { + boolean delta = true; + byte[] score = iterator.next(); + byte[] member = iterator.next(); + + if (options.isNX()) { + if (members.get(member) != null) { + continue; + } + } + if (options.isXX()) { + if (members.get(member) == null) { + continue; + } + } + switch (memberAdd(member, score)) { + case ADDED: + membersAdded++; + makeAddsDeltaInfo(deltaInfo, member, score); + break; + case CHANGED: + // TODO: track changed + makeAddsDeltaInfo(deltaInfo, member, score); + break; + default: + delta = false; + // do nothing + } + + if (delta) { + if (deltaInfo == null) { + deltaInfo = new AddsDeltaInfo(new ArrayList<>()); + } + deltaInfo.add(member); + deltaInfo.add(score); + } + } + if (deltaInfo != null) { + storeChanges(region, key, deltaInfo); + deltaInfo = null; + } + return membersAdded; + } + + byte[] zscore(byte[] member) { + return members.get(member); + } + + private AddsDeltaInfo makeAddsDeltaInfo(AddsDeltaInfo deltaInfo, byte[] member, byte[] score) { + if (deltaInfo == null) { + deltaInfo = new AddsDeltaInfo(new ArrayList<>()); + } + deltaInfo.add(member); + deltaInfo.add(score); + return deltaInfo; + } + + @Override + public RedisDataType getType() { + return REDIS_SORTED_SET; + } + + @Override + protected boolean removeFromRegion() { + return members.isEmpty(); + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), members); + } + + @Override + public String toString() { + return "RedisSet{" + super.toString() + ", " + "members=" + members + '}'; Review comment: This should be `RedisSortedSet`. Also, I know we changed the `toString` for `RedisHash` to just print out the size of the hash... not sure if we want to do that here as well? ########## File path: geode-apis-compatible-with-redis/src/main/java/org/apache/geode/redis/internal/data/RedisSortedSet.java ########## @@ -0,0 +1,286 @@ +/* + * 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.geode.redis.internal.data; + +import static org.apache.geode.redis.internal.data.RedisDataType.REDIS_SORTED_SET; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import it.unimi.dsi.fastutil.bytes.ByteArrays; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenCustomHashMap; + +import org.apache.geode.cache.Region; +import org.apache.geode.internal.InternalDataSerializer; +import org.apache.geode.internal.serialization.DeserializationContext; +import org.apache.geode.internal.serialization.KnownVersion; +import org.apache.geode.internal.serialization.SerializationContext; +import org.apache.geode.redis.internal.delta.AddsDeltaInfo; +import org.apache.geode.redis.internal.delta.DeltaInfo; +import org.apache.geode.redis.internal.delta.RemsDeltaInfo; +import org.apache.geode.redis.internal.executor.sortedset.SortedSetOptions; + +public class RedisSortedSet extends AbstractRedisData { + private Object2ObjectOpenCustomHashMap<byte[], byte[]> members; + + protected static final int BASE_REDIS_SORTED_SET_OVERHEAD = 184; + protected static final int PER_PAIR_OVERHEAD = 48; + + private int sizeInBytes; + + @Override + public int getSizeInBytes() { + return sizeInBytes; + } + + private enum AddOrChange { + ADDED, CHANGED, NOOP + } + + private int calculateSizeOfNewFieldValuePair(byte[] member, byte[] score) { + return PER_PAIR_OVERHEAD + member.length + score.length; + } + + RedisSortedSet(List<byte[]> members) { + sizeInBytes += BASE_REDIS_SORTED_SET_OVERHEAD; + this.members = new Object2ObjectOpenCustomHashMap<>(members.size(), ByteArrays.HASH_STRATEGY); + Iterator<byte[]> iterator = members.iterator(); + + while (iterator.hasNext()) { + byte[] score = iterator.next(); + byte[] member = iterator.next(); + sizeInBytes += calculateSizeOfNewFieldValuePair(member, score); + this.members.put(member, score); + } + } + + RedisSortedSet(List<byte[]> members, SortedSetOptions options) { + if (options.isXX()) { + sizeInBytes += BASE_REDIS_SORTED_SET_OVERHEAD; + this.members = new Object2ObjectOpenCustomHashMap<>(members.size(), ByteArrays.HASH_STRATEGY); + } else { + RedisSortedSet tempSet = new RedisSortedSet(members); + this.members = tempSet.members; + this.sizeInBytes = tempSet.sizeInBytes; + } + } + + // for serialization + public RedisSortedSet() {} + + @Override + protected void applyDelta(DeltaInfo deltaInfo) { + if (deltaInfo instanceof AddsDeltaInfo) { + AddsDeltaInfo addsDeltaInfo = (AddsDeltaInfo) deltaInfo; + membersAddAll(addsDeltaInfo); + } else { + RemsDeltaInfo remsDeltaInfo = (RemsDeltaInfo) deltaInfo; + membersRemoveAll(remsDeltaInfo); + } + } + + /** + * Since GII (getInitialImage) can come in and call toData while other threads are modifying this + * object, the striped executor will not protect toData. So any methods that modify "members" + * needs to be thread safe with toData. + */ + + @Override + public synchronized void toData(DataOutput out, SerializationContext context) throws IOException { + super.toData(out, context); + InternalDataSerializer.writePrimitiveInt(members.size(), out); + for (Map.Entry<byte[], byte[]> entry : members.entrySet()) { + byte[] key = entry.getKey(); + byte[] value = entry.getValue(); + InternalDataSerializer.writeByteArray(key, out); + InternalDataSerializer.writeByteArray(value, out); + } + InternalDataSerializer.writePrimitiveInt(sizeInBytes, out); + } + + @Override + public void fromData(DataInput in, DeserializationContext context) + throws IOException, ClassNotFoundException { + super.fromData(in, context); + int size = InternalDataSerializer.readPrimitiveInt(in); + members = new Object2ObjectOpenCustomHashMap<>(size, ByteArrays.HASH_STRATEGY); + for (int i = 0; i < size; i++) { + members.put(InternalDataSerializer.readByteArray(in), + InternalDataSerializer.readByteArray(in)); + } + sizeInBytes = InternalDataSerializer.readPrimitiveInt(in); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof RedisSortedSet)) { + return false; + } + if (!super.equals(o)) { + return false; + } + RedisSortedSet redisSortedSet = (RedisSortedSet) o; + if (members.size() != redisSortedSet.members.size()) { + return false; + } + + for (Map.Entry<byte[], byte[]> entry : members.entrySet()) { + if (!Arrays.equals(redisSortedSet.members.get(entry.getKey()), (entry.getValue()))) { + return false; + } + } + return true; + } + + @Override + public int getDSFID() { + return REDIS_SORTED_SET_ID; + } + + protected synchronized AddOrChange memberAdd(byte[] memberToAdd, byte[] scoreToAdd) { + boolean added = (members.put(memberToAdd, scoreToAdd) == null); + if (added) { + sizeInBytes += calculateSizeOfNewFieldValuePair(memberToAdd, scoreToAdd); + } Review comment: If the member was changed but not added, we should still calculate the difference in size between the old score value and new score value and add that to `sizeInBytes`. Check out the way we do that in the `hashPut` method of `RedisHash`. ########## File path: geode-apis-compatible-with-redis/src/main/java/org/apache/geode/redis/internal/data/RedisSortedSet.java ########## @@ -0,0 +1,286 @@ +/* + * 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.geode.redis.internal.data; + +import static org.apache.geode.redis.internal.data.RedisDataType.REDIS_SORTED_SET; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import it.unimi.dsi.fastutil.bytes.ByteArrays; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenCustomHashMap; + +import org.apache.geode.cache.Region; +import org.apache.geode.internal.InternalDataSerializer; +import org.apache.geode.internal.serialization.DeserializationContext; +import org.apache.geode.internal.serialization.KnownVersion; +import org.apache.geode.internal.serialization.SerializationContext; +import org.apache.geode.redis.internal.delta.AddsDeltaInfo; +import org.apache.geode.redis.internal.delta.DeltaInfo; +import org.apache.geode.redis.internal.delta.RemsDeltaInfo; +import org.apache.geode.redis.internal.executor.sortedset.SortedSetOptions; + +public class RedisSortedSet extends AbstractRedisData { + private Object2ObjectOpenCustomHashMap<byte[], byte[]> members; + + protected static final int BASE_REDIS_SORTED_SET_OVERHEAD = 184; + protected static final int PER_PAIR_OVERHEAD = 48; + + private int sizeInBytes; + + @Override + public int getSizeInBytes() { + return sizeInBytes; + } + + private enum AddOrChange { + ADDED, CHANGED, NOOP + } + + private int calculateSizeOfNewFieldValuePair(byte[] member, byte[] score) { + return PER_PAIR_OVERHEAD + member.length + score.length; + } + + RedisSortedSet(List<byte[]> members) { + sizeInBytes += BASE_REDIS_SORTED_SET_OVERHEAD; + this.members = new Object2ObjectOpenCustomHashMap<>(members.size(), ByteArrays.HASH_STRATEGY); + Iterator<byte[]> iterator = members.iterator(); + + while (iterator.hasNext()) { + byte[] score = iterator.next(); + byte[] member = iterator.next(); + sizeInBytes += calculateSizeOfNewFieldValuePair(member, score); + this.members.put(member, score); + } + } + + RedisSortedSet(List<byte[]> members, SortedSetOptions options) { + if (options.isXX()) { + sizeInBytes += BASE_REDIS_SORTED_SET_OVERHEAD; + this.members = new Object2ObjectOpenCustomHashMap<>(members.size(), ByteArrays.HASH_STRATEGY); + } else { + RedisSortedSet tempSet = new RedisSortedSet(members); + this.members = tempSet.members; + this.sizeInBytes = tempSet.sizeInBytes; + } + } + + // for serialization + public RedisSortedSet() {} + + @Override + protected void applyDelta(DeltaInfo deltaInfo) { + if (deltaInfo instanceof AddsDeltaInfo) { + AddsDeltaInfo addsDeltaInfo = (AddsDeltaInfo) deltaInfo; + membersAddAll(addsDeltaInfo); + } else { + RemsDeltaInfo remsDeltaInfo = (RemsDeltaInfo) deltaInfo; + membersRemoveAll(remsDeltaInfo); + } + } + + /** + * Since GII (getInitialImage) can come in and call toData while other threads are modifying this + * object, the striped executor will not protect toData. So any methods that modify "members" + * needs to be thread safe with toData. + */ + + @Override + public synchronized void toData(DataOutput out, SerializationContext context) throws IOException { + super.toData(out, context); + InternalDataSerializer.writePrimitiveInt(members.size(), out); + for (Map.Entry<byte[], byte[]> entry : members.entrySet()) { + byte[] key = entry.getKey(); + byte[] value = entry.getValue(); + InternalDataSerializer.writeByteArray(key, out); + InternalDataSerializer.writeByteArray(value, out); + } + InternalDataSerializer.writePrimitiveInt(sizeInBytes, out); + } + + @Override + public void fromData(DataInput in, DeserializationContext context) + throws IOException, ClassNotFoundException { + super.fromData(in, context); + int size = InternalDataSerializer.readPrimitiveInt(in); + members = new Object2ObjectOpenCustomHashMap<>(size, ByteArrays.HASH_STRATEGY); + for (int i = 0; i < size; i++) { + members.put(InternalDataSerializer.readByteArray(in), + InternalDataSerializer.readByteArray(in)); + } + sizeInBytes = InternalDataSerializer.readPrimitiveInt(in); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof RedisSortedSet)) { + return false; + } + if (!super.equals(o)) { + return false; + } + RedisSortedSet redisSortedSet = (RedisSortedSet) o; + if (members.size() != redisSortedSet.members.size()) { + return false; + } + + for (Map.Entry<byte[], byte[]> entry : members.entrySet()) { + if (!Arrays.equals(redisSortedSet.members.get(entry.getKey()), (entry.getValue()))) { + return false; + } + } + return true; + } + + @Override + public int getDSFID() { + return REDIS_SORTED_SET_ID; + } + + protected synchronized AddOrChange memberAdd(byte[] memberToAdd, byte[] scoreToAdd) { + boolean added = (members.put(memberToAdd, scoreToAdd) == null); + if (added) { + sizeInBytes += calculateSizeOfNewFieldValuePair(memberToAdd, scoreToAdd); + } + return added ? AddOrChange.ADDED : AddOrChange.NOOP; + } + + private synchronized void membersAddAll(AddsDeltaInfo addsDeltaInfo) { + Iterator<byte[]> iterator = addsDeltaInfo.getAdds().iterator(); + while (iterator.hasNext()) { + byte[] member = iterator.next(); + sizeInBytes += PER_PAIR_OVERHEAD + member.length; + byte[] score = iterator.next(); + sizeInBytes += PER_PAIR_OVERHEAD + score.length; + members.put(member, score); + } + } + + + private synchronized void membersRemoveAll(RemsDeltaInfo remsDeltaInfo) { + for (byte[] member : remsDeltaInfo.getRemoves()) { + sizeInBytes -= (PER_PAIR_OVERHEAD + member.length); Review comment: We should use the `calculateSizeOfNewFieldValuePair` here and subtract that.... maybe the method could be renamed to `calculateSizeOfFieldValuePair` since it's not always new. Also, seems like we should be iterating through the delta info to get the `member` and `score` and remove both of those like we did for `membersAddAll` ########## File path: geode-apis-compatible-with-redis/src/main/java/org/apache/geode/redis/internal/data/RedisSortedSet.java ########## @@ -0,0 +1,286 @@ +/* + * 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.geode.redis.internal.data; + +import static org.apache.geode.redis.internal.data.RedisDataType.REDIS_SORTED_SET; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import it.unimi.dsi.fastutil.bytes.ByteArrays; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenCustomHashMap; + +import org.apache.geode.cache.Region; +import org.apache.geode.internal.InternalDataSerializer; +import org.apache.geode.internal.serialization.DeserializationContext; +import org.apache.geode.internal.serialization.KnownVersion; +import org.apache.geode.internal.serialization.SerializationContext; +import org.apache.geode.redis.internal.delta.AddsDeltaInfo; +import org.apache.geode.redis.internal.delta.DeltaInfo; +import org.apache.geode.redis.internal.delta.RemsDeltaInfo; +import org.apache.geode.redis.internal.executor.sortedset.SortedSetOptions; + +public class RedisSortedSet extends AbstractRedisData { + private Object2ObjectOpenCustomHashMap<byte[], byte[]> members; + + protected static final int BASE_REDIS_SORTED_SET_OVERHEAD = 184; + protected static final int PER_PAIR_OVERHEAD = 48; + + private int sizeInBytes; Review comment: We changed `RedisHash` so the `sizeInBytes` is initialized to the base overhead. I think we could do the same here and remove it from the constructors. ########## File path: geode-apis-compatible-with-redis/src/main/java/org/apache/geode/redis/internal/data/RedisSortedSet.java ########## @@ -0,0 +1,286 @@ +/* + * 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.geode.redis.internal.data; + +import static org.apache.geode.redis.internal.data.RedisDataType.REDIS_SORTED_SET; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import it.unimi.dsi.fastutil.bytes.ByteArrays; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenCustomHashMap; + +import org.apache.geode.cache.Region; +import org.apache.geode.internal.InternalDataSerializer; +import org.apache.geode.internal.serialization.DeserializationContext; +import org.apache.geode.internal.serialization.KnownVersion; +import org.apache.geode.internal.serialization.SerializationContext; +import org.apache.geode.redis.internal.delta.AddsDeltaInfo; +import org.apache.geode.redis.internal.delta.DeltaInfo; +import org.apache.geode.redis.internal.delta.RemsDeltaInfo; +import org.apache.geode.redis.internal.executor.sortedset.SortedSetOptions; + +public class RedisSortedSet extends AbstractRedisData { + private Object2ObjectOpenCustomHashMap<byte[], byte[]> members; + + protected static final int BASE_REDIS_SORTED_SET_OVERHEAD = 184; + protected static final int PER_PAIR_OVERHEAD = 48; + + private int sizeInBytes; + + @Override + public int getSizeInBytes() { + return sizeInBytes; + } + + private enum AddOrChange { + ADDED, CHANGED, NOOP + } + + private int calculateSizeOfNewFieldValuePair(byte[] member, byte[] score) { + return PER_PAIR_OVERHEAD + member.length + score.length; + } + + RedisSortedSet(List<byte[]> members) { + sizeInBytes += BASE_REDIS_SORTED_SET_OVERHEAD; + this.members = new Object2ObjectOpenCustomHashMap<>(members.size(), ByteArrays.HASH_STRATEGY); + Iterator<byte[]> iterator = members.iterator(); + + while (iterator.hasNext()) { + byte[] score = iterator.next(); + byte[] member = iterator.next(); + sizeInBytes += calculateSizeOfNewFieldValuePair(member, score); + this.members.put(member, score); + } + } + + RedisSortedSet(List<byte[]> members, SortedSetOptions options) { + if (options.isXX()) { + sizeInBytes += BASE_REDIS_SORTED_SET_OVERHEAD; + this.members = new Object2ObjectOpenCustomHashMap<>(members.size(), ByteArrays.HASH_STRATEGY); + } else { + RedisSortedSet tempSet = new RedisSortedSet(members); + this.members = tempSet.members; + this.sizeInBytes = tempSet.sizeInBytes; + } + } + + // for serialization + public RedisSortedSet() {} + + @Override + protected void applyDelta(DeltaInfo deltaInfo) { + if (deltaInfo instanceof AddsDeltaInfo) { + AddsDeltaInfo addsDeltaInfo = (AddsDeltaInfo) deltaInfo; + membersAddAll(addsDeltaInfo); + } else { + RemsDeltaInfo remsDeltaInfo = (RemsDeltaInfo) deltaInfo; + membersRemoveAll(remsDeltaInfo); + } + } + + /** + * Since GII (getInitialImage) can come in and call toData while other threads are modifying this + * object, the striped executor will not protect toData. So any methods that modify "members" + * needs to be thread safe with toData. + */ + + @Override + public synchronized void toData(DataOutput out, SerializationContext context) throws IOException { + super.toData(out, context); + InternalDataSerializer.writePrimitiveInt(members.size(), out); + for (Map.Entry<byte[], byte[]> entry : members.entrySet()) { + byte[] key = entry.getKey(); + byte[] value = entry.getValue(); + InternalDataSerializer.writeByteArray(key, out); + InternalDataSerializer.writeByteArray(value, out); + } + InternalDataSerializer.writePrimitiveInt(sizeInBytes, out); + } + + @Override + public void fromData(DataInput in, DeserializationContext context) + throws IOException, ClassNotFoundException { + super.fromData(in, context); + int size = InternalDataSerializer.readPrimitiveInt(in); + members = new Object2ObjectOpenCustomHashMap<>(size, ByteArrays.HASH_STRATEGY); + for (int i = 0; i < size; i++) { + members.put(InternalDataSerializer.readByteArray(in), + InternalDataSerializer.readByteArray(in)); + } + sizeInBytes = InternalDataSerializer.readPrimitiveInt(in); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof RedisSortedSet)) { + return false; + } + if (!super.equals(o)) { + return false; + } + RedisSortedSet redisSortedSet = (RedisSortedSet) o; + if (members.size() != redisSortedSet.members.size()) { + return false; + } + + for (Map.Entry<byte[], byte[]> entry : members.entrySet()) { + if (!Arrays.equals(redisSortedSet.members.get(entry.getKey()), (entry.getValue()))) { + return false; + } + } + return true; + } + + @Override + public int getDSFID() { + return REDIS_SORTED_SET_ID; + } + + protected synchronized AddOrChange memberAdd(byte[] memberToAdd, byte[] scoreToAdd) { + boolean added = (members.put(memberToAdd, scoreToAdd) == null); + if (added) { + sizeInBytes += calculateSizeOfNewFieldValuePair(memberToAdd, scoreToAdd); + } + return added ? AddOrChange.ADDED : AddOrChange.NOOP; + } + + private synchronized void membersAddAll(AddsDeltaInfo addsDeltaInfo) { + Iterator<byte[]> iterator = addsDeltaInfo.getAdds().iterator(); + while (iterator.hasNext()) { + byte[] member = iterator.next(); + sizeInBytes += PER_PAIR_OVERHEAD + member.length; + byte[] score = iterator.next(); + sizeInBytes += PER_PAIR_OVERHEAD + score.length; + members.put(member, score); + } + } + + + private synchronized void membersRemoveAll(RemsDeltaInfo remsDeltaInfo) { + for (byte[] member : remsDeltaInfo.getRemoves()) { + sizeInBytes -= (PER_PAIR_OVERHEAD + member.length); + members.remove(member); + } + } + + /** + * @param region the region this instance is stored in + * @param key the name of the set to add to + * @param membersToAdd members to add to this set; NOTE this list may by modified by this call + * @return the number of members actually added + */ + long zadd(Region<RedisKey, RedisData> region, RedisKey key, List<byte[]> membersToAdd, + SortedSetOptions options) { + int membersAdded = 0; + if (options == null) { + options = new SortedSetOptions(SortedSetOptions.Exists.NONE, SortedSetOptions.Update.NONE); + } Review comment: This would never happen since we create `SortedSetOptions` when we call `zadd` from the executor. ########## File path: geode-apis-compatible-with-redis/src/main/java/org/apache/geode/redis/internal/data/RedisSortedSet.java ########## @@ -0,0 +1,286 @@ +/* + * 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.geode.redis.internal.data; + +import static org.apache.geode.redis.internal.data.RedisDataType.REDIS_SORTED_SET; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import it.unimi.dsi.fastutil.bytes.ByteArrays; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenCustomHashMap; + +import org.apache.geode.cache.Region; +import org.apache.geode.internal.InternalDataSerializer; +import org.apache.geode.internal.serialization.DeserializationContext; +import org.apache.geode.internal.serialization.KnownVersion; +import org.apache.geode.internal.serialization.SerializationContext; +import org.apache.geode.redis.internal.delta.AddsDeltaInfo; +import org.apache.geode.redis.internal.delta.DeltaInfo; +import org.apache.geode.redis.internal.delta.RemsDeltaInfo; +import org.apache.geode.redis.internal.executor.sortedset.SortedSetOptions; + +public class RedisSortedSet extends AbstractRedisData { + private Object2ObjectOpenCustomHashMap<byte[], byte[]> members; + + protected static final int BASE_REDIS_SORTED_SET_OVERHEAD = 184; + protected static final int PER_PAIR_OVERHEAD = 48; + + private int sizeInBytes; + + @Override + public int getSizeInBytes() { + return sizeInBytes; + } + + private enum AddOrChange { + ADDED, CHANGED, NOOP + } + + private int calculateSizeOfNewFieldValuePair(byte[] member, byte[] score) { + return PER_PAIR_OVERHEAD + member.length + score.length; + } + + RedisSortedSet(List<byte[]> members) { + sizeInBytes += BASE_REDIS_SORTED_SET_OVERHEAD; + this.members = new Object2ObjectOpenCustomHashMap<>(members.size(), ByteArrays.HASH_STRATEGY); + Iterator<byte[]> iterator = members.iterator(); + + while (iterator.hasNext()) { + byte[] score = iterator.next(); + byte[] member = iterator.next(); + sizeInBytes += calculateSizeOfNewFieldValuePair(member, score); + this.members.put(member, score); + } + } + + RedisSortedSet(List<byte[]> members, SortedSetOptions options) { + if (options.isXX()) { + sizeInBytes += BASE_REDIS_SORTED_SET_OVERHEAD; + this.members = new Object2ObjectOpenCustomHashMap<>(members.size(), ByteArrays.HASH_STRATEGY); + } else { + RedisSortedSet tempSet = new RedisSortedSet(members); + this.members = tempSet.members; + this.sizeInBytes = tempSet.sizeInBytes; + } + } + + // for serialization + public RedisSortedSet() {} + + @Override + protected void applyDelta(DeltaInfo deltaInfo) { + if (deltaInfo instanceof AddsDeltaInfo) { + AddsDeltaInfo addsDeltaInfo = (AddsDeltaInfo) deltaInfo; + membersAddAll(addsDeltaInfo); + } else { + RemsDeltaInfo remsDeltaInfo = (RemsDeltaInfo) deltaInfo; + membersRemoveAll(remsDeltaInfo); + } + } + + /** + * Since GII (getInitialImage) can come in and call toData while other threads are modifying this + * object, the striped executor will not protect toData. So any methods that modify "members" + * needs to be thread safe with toData. + */ + + @Override + public synchronized void toData(DataOutput out, SerializationContext context) throws IOException { + super.toData(out, context); + InternalDataSerializer.writePrimitiveInt(members.size(), out); + for (Map.Entry<byte[], byte[]> entry : members.entrySet()) { + byte[] key = entry.getKey(); + byte[] value = entry.getValue(); + InternalDataSerializer.writeByteArray(key, out); + InternalDataSerializer.writeByteArray(value, out); + } + InternalDataSerializer.writePrimitiveInt(sizeInBytes, out); + } + + @Override + public void fromData(DataInput in, DeserializationContext context) + throws IOException, ClassNotFoundException { + super.fromData(in, context); + int size = InternalDataSerializer.readPrimitiveInt(in); + members = new Object2ObjectOpenCustomHashMap<>(size, ByteArrays.HASH_STRATEGY); + for (int i = 0; i < size; i++) { + members.put(InternalDataSerializer.readByteArray(in), + InternalDataSerializer.readByteArray(in)); + } + sizeInBytes = InternalDataSerializer.readPrimitiveInt(in); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof RedisSortedSet)) { + return false; + } + if (!super.equals(o)) { + return false; + } + RedisSortedSet redisSortedSet = (RedisSortedSet) o; + if (members.size() != redisSortedSet.members.size()) { + return false; + } + + for (Map.Entry<byte[], byte[]> entry : members.entrySet()) { + if (!Arrays.equals(redisSortedSet.members.get(entry.getKey()), (entry.getValue()))) { + return false; + } + } + return true; + } + + @Override + public int getDSFID() { + return REDIS_SORTED_SET_ID; + } + + protected synchronized AddOrChange memberAdd(byte[] memberToAdd, byte[] scoreToAdd) { + boolean added = (members.put(memberToAdd, scoreToAdd) == null); + if (added) { + sizeInBytes += calculateSizeOfNewFieldValuePair(memberToAdd, scoreToAdd); + } + return added ? AddOrChange.ADDED : AddOrChange.NOOP; + } + + private synchronized void membersAddAll(AddsDeltaInfo addsDeltaInfo) { + Iterator<byte[]> iterator = addsDeltaInfo.getAdds().iterator(); + while (iterator.hasNext()) { + byte[] member = iterator.next(); + sizeInBytes += PER_PAIR_OVERHEAD + member.length; + byte[] score = iterator.next(); + sizeInBytes += PER_PAIR_OVERHEAD + score.length; + members.put(member, score); + } + } + + + private synchronized void membersRemoveAll(RemsDeltaInfo remsDeltaInfo) { + for (byte[] member : remsDeltaInfo.getRemoves()) { + sizeInBytes -= (PER_PAIR_OVERHEAD + member.length); + members.remove(member); + } + } + + /** + * @param region the region this instance is stored in + * @param key the name of the set to add to + * @param membersToAdd members to add to this set; NOTE this list may by modified by this call + * @return the number of members actually added + */ + long zadd(Region<RedisKey, RedisData> region, RedisKey key, List<byte[]> membersToAdd, + SortedSetOptions options) { + int membersAdded = 0; + if (options == null) { + options = new SortedSetOptions(SortedSetOptions.Exists.NONE, SortedSetOptions.Update.NONE); + } + AddsDeltaInfo deltaInfo = null; + Iterator<byte[]> iterator = membersToAdd.iterator(); + while (iterator.hasNext()) { + boolean delta = true; + byte[] score = iterator.next(); + byte[] member = iterator.next(); + + if (options.isNX()) { + if (members.get(member) != null) { + continue; + } + } + if (options.isXX()) { + if (members.get(member) == null) { + continue; + } + } Review comment: You could utilize `members.containsKey()` for these and make the conditional &&: ``` if (options.isNX() && members.containsKey(member)) { continue; } ``` ########## File path: geode-apis-compatible-with-redis/src/main/java/org/apache/geode/redis/internal/data/RedisSortedSet.java ########## @@ -0,0 +1,286 @@ +/* + * 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.geode.redis.internal.data; + +import static org.apache.geode.redis.internal.data.RedisDataType.REDIS_SORTED_SET; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import it.unimi.dsi.fastutil.bytes.ByteArrays; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenCustomHashMap; + +import org.apache.geode.cache.Region; +import org.apache.geode.internal.InternalDataSerializer; +import org.apache.geode.internal.serialization.DeserializationContext; +import org.apache.geode.internal.serialization.KnownVersion; +import org.apache.geode.internal.serialization.SerializationContext; +import org.apache.geode.redis.internal.delta.AddsDeltaInfo; +import org.apache.geode.redis.internal.delta.DeltaInfo; +import org.apache.geode.redis.internal.delta.RemsDeltaInfo; +import org.apache.geode.redis.internal.executor.sortedset.SortedSetOptions; + +public class RedisSortedSet extends AbstractRedisData { + private Object2ObjectOpenCustomHashMap<byte[], byte[]> members; + + protected static final int BASE_REDIS_SORTED_SET_OVERHEAD = 184; + protected static final int PER_PAIR_OVERHEAD = 48; + + private int sizeInBytes; + + @Override + public int getSizeInBytes() { + return sizeInBytes; + } + + private enum AddOrChange { + ADDED, CHANGED, NOOP + } + + private int calculateSizeOfNewFieldValuePair(byte[] member, byte[] score) { + return PER_PAIR_OVERHEAD + member.length + score.length; + } + + RedisSortedSet(List<byte[]> members) { + sizeInBytes += BASE_REDIS_SORTED_SET_OVERHEAD; + this.members = new Object2ObjectOpenCustomHashMap<>(members.size(), ByteArrays.HASH_STRATEGY); + Iterator<byte[]> iterator = members.iterator(); + + while (iterator.hasNext()) { + byte[] score = iterator.next(); + byte[] member = iterator.next(); + sizeInBytes += calculateSizeOfNewFieldValuePair(member, score); + this.members.put(member, score); + } + } + + RedisSortedSet(List<byte[]> members, SortedSetOptions options) { + if (options.isXX()) { + sizeInBytes += BASE_REDIS_SORTED_SET_OVERHEAD; + this.members = new Object2ObjectOpenCustomHashMap<>(members.size(), ByteArrays.HASH_STRATEGY); + } else { + RedisSortedSet tempSet = new RedisSortedSet(members); + this.members = tempSet.members; + this.sizeInBytes = tempSet.sizeInBytes; + } + } + + // for serialization + public RedisSortedSet() {} + + @Override + protected void applyDelta(DeltaInfo deltaInfo) { + if (deltaInfo instanceof AddsDeltaInfo) { + AddsDeltaInfo addsDeltaInfo = (AddsDeltaInfo) deltaInfo; + membersAddAll(addsDeltaInfo); + } else { + RemsDeltaInfo remsDeltaInfo = (RemsDeltaInfo) deltaInfo; + membersRemoveAll(remsDeltaInfo); + } + } + + /** + * Since GII (getInitialImage) can come in and call toData while other threads are modifying this + * object, the striped executor will not protect toData. So any methods that modify "members" + * needs to be thread safe with toData. + */ + + @Override + public synchronized void toData(DataOutput out, SerializationContext context) throws IOException { + super.toData(out, context); + InternalDataSerializer.writePrimitiveInt(members.size(), out); + for (Map.Entry<byte[], byte[]> entry : members.entrySet()) { + byte[] key = entry.getKey(); + byte[] value = entry.getValue(); + InternalDataSerializer.writeByteArray(key, out); + InternalDataSerializer.writeByteArray(value, out); + } + InternalDataSerializer.writePrimitiveInt(sizeInBytes, out); + } + + @Override + public void fromData(DataInput in, DeserializationContext context) + throws IOException, ClassNotFoundException { + super.fromData(in, context); + int size = InternalDataSerializer.readPrimitiveInt(in); + members = new Object2ObjectOpenCustomHashMap<>(size, ByteArrays.HASH_STRATEGY); + for (int i = 0; i < size; i++) { + members.put(InternalDataSerializer.readByteArray(in), + InternalDataSerializer.readByteArray(in)); + } + sizeInBytes = InternalDataSerializer.readPrimitiveInt(in); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof RedisSortedSet)) { + return false; + } + if (!super.equals(o)) { + return false; + } + RedisSortedSet redisSortedSet = (RedisSortedSet) o; + if (members.size() != redisSortedSet.members.size()) { + return false; + } + + for (Map.Entry<byte[], byte[]> entry : members.entrySet()) { + if (!Arrays.equals(redisSortedSet.members.get(entry.getKey()), (entry.getValue()))) { + return false; + } + } + return true; + } + + @Override + public int getDSFID() { + return REDIS_SORTED_SET_ID; + } + + protected synchronized AddOrChange memberAdd(byte[] memberToAdd, byte[] scoreToAdd) { + boolean added = (members.put(memberToAdd, scoreToAdd) == null); + if (added) { + sizeInBytes += calculateSizeOfNewFieldValuePair(memberToAdd, scoreToAdd); + } + return added ? AddOrChange.ADDED : AddOrChange.NOOP; + } + + private synchronized void membersAddAll(AddsDeltaInfo addsDeltaInfo) { + Iterator<byte[]> iterator = addsDeltaInfo.getAdds().iterator(); + while (iterator.hasNext()) { + byte[] member = iterator.next(); + sizeInBytes += PER_PAIR_OVERHEAD + member.length; + byte[] score = iterator.next(); + sizeInBytes += PER_PAIR_OVERHEAD + score.length; + members.put(member, score); + } + } + + + private synchronized void membersRemoveAll(RemsDeltaInfo remsDeltaInfo) { + for (byte[] member : remsDeltaInfo.getRemoves()) { + sizeInBytes -= (PER_PAIR_OVERHEAD + member.length); + members.remove(member); + } + } + + /** + * @param region the region this instance is stored in + * @param key the name of the set to add to + * @param membersToAdd members to add to this set; NOTE this list may by modified by this call + * @return the number of members actually added + */ + long zadd(Region<RedisKey, RedisData> region, RedisKey key, List<byte[]> membersToAdd, Review comment: I think we could clean up this method a lot. We need to set the delta info whether or not it was changed or added (currently change is set as `NOOP` (from me, which will fall into the `default` in the case switch and set the delta to false). We could do something like this: ``` protected synchronized byte[] memberAdd(byte[] memberToAdd, byte[] scoreToAdd) { byte[] oldScore = members.put(memberToAdd, scoreToAdd); if (oldScore == null) { sizeInBytes += calculateSizeOfNewFieldValuePair(memberToAdd, scoreToAdd); } else { sizeInBytes += scoreToAdd.length - oldScore.length; } return oldScore; } long zadd(Region<RedisKey, RedisData> region, RedisKey key, List<byte[]> membersToAdd, SortedSetOptions options) { int membersAdded = 0; if (options == null) { options = new SortedSetOptions(SortedSetOptions.Exists.NONE, SortedSetOptions.Update.NONE); } Iterator<byte[]> iterator = membersToAdd.iterator(); AddsDeltaInfo deltaInfo = null; while (iterator.hasNext()) { byte[] score = iterator.next(); byte[] member = iterator.next(); boolean newMember; if (options.isNX() && members.containsKey(member)) { continue; } if (options.isXX() && !members.containsKey(member)) { continue; } newMember = memberAdd(member, score) == null; // right now we don't need to worry about the changed option since we haven't added that yet... // we can change the if case once that's added. if (newMember) { membersAdded++; } // we need to add deltaInfo whether it was a new member or a changed member, we won't hit // this if we didn't add at all since we put `continue` for those cases // there did not seem to be a clean way to extract this to a method if (deltaInfo == null) { deltaInfo = new AddsDeltaInfo(new ArrayList<>()); } deltaInfo.add(member); deltaInfo.add(score); } // store changes will check to make sure deltaInfo is not null storeChanges(region, key, deltaInfo); return membersAdded; } ########## File path: geode-apis-compatible-with-redis/src/main/java/org/apache/geode/redis/internal/ParameterRequirements/ZAddParameterRequirements.java ########## @@ -0,0 +1,116 @@ +/* + * 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.geode.redis.internal.ParameterRequirements; + +import static org.apache.geode.redis.internal.RedisConstants.ERROR_INVALID_ZADD_OPTION_NX_XX; +import static org.apache.geode.redis.internal.RedisConstants.ERROR_NOT_A_VALID_FLOAT; +import static org.apache.geode.redis.internal.RedisConstants.ERROR_SYNTAX; + +import java.util.Iterator; +import java.util.List; + +import org.apache.geode.redis.internal.netty.Coder; +import org.apache.geode.redis.internal.netty.Command; +import org.apache.geode.redis.internal.netty.ExecutionHandlerContext; + +public class ZAddParameterRequirements implements ParameterRequirements { + @Override + public void checkParameters(Command command, ExecutionHandlerContext context) { + int numberOfArguments = command.getProcessedCommand().size(); + + if (numberOfArguments < 4) { + throw new RedisParametersMismatchException(command.wrongNumberOfArgumentsErrorMessage()); + } + + int optionsFoundCount = confirmKnownSubcommands(command); + + if ((numberOfArguments - optionsFoundCount - 2) % 2 != 0) { + throw new RedisParametersMismatchException(ERROR_SYNTAX); + } + } + + private int confirmKnownSubcommands(Command command) { Review comment: This could be called `confirmKnownOptions` since these aren't really subcommands. -- 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. For queries about this service, please contact Infrastructure at: us...@infra.apache.org