allthingssecurity commented on code in PR #30905:
URL: https://github.com/apache/camel/pull/30905#discussion_r4714764175


##########
components/camel-redis/src/main/java/org/apache/camel/component/redis/processor/aggregate/RedisAggregationRepository.java:
##########
@@ -52,6 +54,7 @@
 import org.redisson.client.codec.ByteArrayCodec;
 import org.redisson.client.codec.Codec;
 import org.redisson.client.codec.StringCodec;
+import org.redisson.client.handler.State;

Review Comment:
   Done in ca8c4e1c9faa: a comment at the decode call says State is a parameter 
of the Decoder.decode(ByteBuf, State) codec contract of Redisson. I put it at 
the call rather than on the import line, so the import sort stays clean.



##########
components/camel-redis/src/test/java/org/apache/camel/component/redis/processor/aggregate/RedisAggregationRepositoryOptimisticTest.java:
##########
@@ -0,0 +1,604 @@
+/*
+ * 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.camel.component.redis.processor.aggregate;
+
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.Unpooled;
+import org.apache.camel.AggregationStrategy;
+import org.apache.camel.Exchange;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.processor.aggregate.OptimisticLockRetryPolicy;
+import 
org.apache.camel.spi.OptimisticLockingAggregationRepository.OptimisticLockingException;
+import org.apache.camel.support.DefaultExchange;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.redisson.api.RMap;
+import org.redisson.api.RScript;
+import org.redisson.api.RedissonClient;
+import org.redisson.client.codec.ByteArrayCodec;
+import org.redisson.client.codec.Codec;
+import org.redisson.client.handler.State;
+import org.redisson.codec.Kryo5Codec;
+import org.redisson.codec.SerializationCodec;
+import org.redisson.config.Config;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * The repository with optimistic locking through the Aggregate EIP, with an 
in-memory stand-in for the Redis hashes
+ * that stores the values encoded by the codec of the hash and compares them 
by their bytes, as Redis does.
+ */
+public class RedisAggregationRepositoryOptimisticTest extends CamelTestSupport 
{
+
+    /** Changes the old exchange and returns it, as the Aggregate EIP 
documentation shows. */
+    private static final AggregationStrategy CHANGE_OLD = (oldExchange, 
newExchange) -> {
+        if (oldExchange == null) {
+            return newExchange;
+        }
+        oldExchange.getIn().setBody(join(oldExchange, newExchange));
+        return oldExchange;
+    };
+
+    /** Leaves the old exchange as it is and returns the new exchange. */
+    private static final AggregationStrategy RETURN_NEW = (oldExchange, 
newExchange) -> {
+        if (oldExchange != null) {
+            newExchange.getIn().setBody(join(oldExchange, newExchange));
+        }
+        return newExchange;
+    };
+
+    /** Keeps a list body and adds the new message to it in place. */
+    @SuppressWarnings("unchecked")
+    private static final AggregationStrategy ADD_TO_LIST = (oldExchange, 
newExchange) -> {
+        if (oldExchange == null) {
+            List<String> list = new ArrayList<>();
+            list.add(newExchange.getIn().getBody(String.class));
+            newExchange.getIn().setBody(list);
+            return newExchange;
+        }
+        
oldExchange.getIn().getBody(List.class).add(newExchange.getIn().getBody(String.class));
+        return oldExchange;
+    };
+
+    /** Keeps a HashSet body and adds the new message to it in place. */
+    @SuppressWarnings("unchecked")
+    private static final AggregationStrategy ADD_TO_SET = (oldExchange, 
newExchange) -> {
+        if (oldExchange == null) {
+            Set<String> set = new HashSet<>();
+            set.add(newExchange.getIn().getBody(String.class));
+            newExchange.getIn().setBody(set);
+            return newExchange;
+        }
+        
oldExchange.getIn().getBody(Set.class).add(newExchange.getIn().getBody(String.class));
+        return oldExchange;
+    };
+
+    // the Redis hashes, guarded by themselves as Redis runs one command or 
script at a time
+    private final Map<String, Map<String, Object>> redis = new HashMap<>();
+    // the codec of each hash, to read the fields that the script is given
+    private final Map<String, Codec> codecs = new HashMap<>();
+    private RedissonClient redisson;
+    private final List<RedisAggregationRepository> repositories = new 
ArrayList<>();
+
+    @BeforeEach
+    void createRedis() {
+        redisson = mock(RedissonClient.class);
+        when(redisson.<String, Object> getMap(anyString(), any(Codec.class)))
+                .thenAnswer(i -> {
+                    synchronized (redis) {
+                        codecs.put(i.getArgument(0), i.getArgument(1));
+                    }
+                    return inMemoryMap(hash(i.getArgument(0)), 
i.getArgument(1));
+                });
+        Config config = mock(Config.class);
+        when(redisson.getConfig()).thenReturn(config);
+        RScript script = mock(RScript.class);
+        when(redisson.getScript(ByteArrayCodec.INSTANCE)).thenReturn(script);
+        when(script.eval(any(RScript.Mode.class), anyString(), 
any(RScript.ReturnType.class), anyList(),
+                any(Object[].class)))
+                .thenAnswer(i -> {
+                    Object[] args = i.getArguments();
+                    Object[] values = args.length == 5 && args[4] instanceof 
Object[] array
+                            ? array : Arrays.copyOfRange(args, 4, args.length);
+                    return optimisticRemoveScript(i.getArgument(1), 
i.getArgument(3), values);
+                });
+    }
+
+    @AfterEach
+    void stopRepositories() {
+        repositories.forEach(RedisAggregationRepository::stop);
+    }
+
+    @Test
+    void testCompletionSizeWithStrategyThatChangesOldExchange() throws 
Exception {
+        assertGroupsComplete("changeOld", CHANGE_OLD, true);
+    }
+
+    @Test
+    void testCompletionSizeWithStrategyThatChangesOldExchangeWithoutRecovery() 
throws Exception {
+        assertGroupsComplete("changeOldNoRecovery", CHANGE_OLD, false);
+    }
+
+    @Test
+    void testCompletionSizeWithStrategyThatReturnsNewExchangeWithoutRecovery() 
throws Exception {
+        assertGroupsComplete("returnNewNoRecovery", RETURN_NEW, false);
+    }
+
+    @Test
+    void testCompletionSizeWithCodecAndStrategyThatChangesTheBodyInPlace() 
throws Exception {
+        // the exchange that get() returns must not share the body with the 
value it read and compares with
+        String name = "codecInPlace";
+        RedisAggregationRepository repository = repository(name, true, new 
Kryo5Codec());
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                from("direct:" + name)
+                        .aggregate(header("id"), 
ADD_TO_LIST).aggregationRepository(repository)
+                        
.optimisticLocking().optimisticLockRetryPolicy(retryPolicy())
+                        .completionSize(3)
+                        .to("mock:" + name);
+            }
+        });
+        MockEndpoint mock = getMockEndpoint("mock:" + name);
+        mock.expectedBodiesReceivedInAnyOrder(List.of("a", "b", "c"), 
List.of("d", "e", "f"));
+
+        for (String body : List.of("a", "d", "b", "e", "c", "f")) {
+            template.sendBodyAndHeader("direct:" + name, body, "id", 
"abc".contains(body) ? "K1" : "K2");
+        }
+
+        MockEndpoint.assertIsSatisfied(context, 20, TimeUnit.SECONDS);
+        assertTrue(hash(name).isEmpty(), "groups left: " + 
hash(name).keySet());
+        await().atMost(10, TimeUnit.SECONDS).until(() -> hash(name + 
"-completed").isEmpty());
+    }
+
+    @Test
+    void testCompletionSizeWithKryoCodecAndHashSetBody() throws Exception {
+        // Kryo reads a HashSet back with another capacity, so the decoded 
group encoded again has its elements in
+        // another order once the set has a dozen of them: the compare must 
use the bytes that were read
+        completeOneGroupWithCodec("kryoHashSet", new Kryo5Codec(), ADD_TO_SET, 
20);
+    }
+
+    @Test
+    void testCompletionSizeWithSerializationCodec() throws Exception {
+        // Java serialization of a HashMap writes its capacity, which the 
decoded group does not keep, so the decoded
+        // group encoded again differs from the stored bytes from the second 
message on
+        completeOneGroupWithCodec("serializationCodec", new 
SerializationCodec(), ADD_TO_LIST, 3);
+    }
+
+    @Test
+    void testCompletionTimeout() throws Exception {
+        RedisAggregationRepository repository = repository("timeout", true);
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                from("direct:timeout")
+                        .aggregate(header("id"), 
CHANGE_OLD).aggregationRepository(repository)
+                        
.optimisticLocking().optimisticLockRetryPolicy(retryPolicy())
+                        
.completionTimeout(200).completionTimeoutCheckerInterval(50)
+                        .to("mock:timeout");
+            }
+        });
+        MockEndpoint mock = getMockEndpoint("mock:timeout");
+        mock.expectedBodiesReceivedInAnyOrder("a", "b+c");
+
+        template.sendBodyAndHeader("direct:timeout", "a", "id", "K1");
+        template.sendBodyAndHeader("direct:timeout", "b", "id", "K2");
+        template.sendBodyAndHeader("direct:timeout", "c", "id", "K2");
+
+        MockEndpoint.assertIsSatisfied(context, 20, TimeUnit.SECONDS);
+        assertTrue(hash("timeout").isEmpty(), "groups left: " + 
hash("timeout").keySet());
+        await().atMost(10, TimeUnit.SECONDS).until(() -> 
hash("timeout-completed").isEmpty());
+    }
+
+    @Test
+    void testTwoRepositoriesSharingTheHashes() throws Exception {

Review Comment:
   Done in ca8c4e1c9faa: the test has a Javadoc now (two repositories on the 
same hashes, 20 keys sent from 4 threads, so both update the same groups at the 
same time).



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to