Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Java: Add transaction requests for standalone and cluster-mode #70

Closed
Show file tree
Hide file tree
Changes from 24 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
f296c00
Add cluster client, request routes configuration and support for bulk…
Yury-Fridlyand Jan 27, 2024
ef78f40
Add cluster client and routes support for cluster client.
Yury-Fridlyand Jan 11, 2024
3fac54b
Address PR feedback and add tests.
Yury-Fridlyand Jan 25, 2024
156765b
Add transactions for single and multi-cluster clients
acarbonetto Jan 26, 2024
ec3a76a
Fix unit tests
acarbonetto Jan 27, 2024
6d308d2
Add Transactions on top of cluster mode
acarbonetto Jan 29, 2024
1ea0060
Address PR feedback.
Yury-Fridlyand Jan 29, 2024
e9b4947
Add BaseTransaction
acarbonetto Jan 29, 2024
5a62abc
Merge branch 'java/integ_yuryf_cluster_bulk_resp' into java/dev_acarb…
acarbonetto Jan 30, 2024
80484ed
Documentation fixes
acarbonetto Jan 30, 2024
65d6e17
Move protobuf build calls back to command manager
acarbonetto Jan 30, 2024
fa3713e
Update tests
acarbonetto Jan 31, 2024
8f33d2b
Clean up tests
acarbonetto Jan 31, 2024
a7bf0a3
Change return type of info() to String
acarbonetto Jan 31, 2024
4e4870c
Update the javadocs
acarbonetto Jan 31, 2024
49ed65e
Update the javadocs
acarbonetto Jan 31, 2024
dcbaec4
Spotless
acarbonetto Jan 31, 2024
4940950
Updates for comments
acarbonetto Jan 31, 2024
87ec173
Move RequestType to it's own class
acarbonetto Jan 31, 2024
55554f0
Update javadoc @Returns
acarbonetto Jan 31, 2024
43ec3d8
Clean up test
acarbonetto Jan 31, 2024
8eb9ea2
Merge branch 'java/integ_acarbo_api_transactions' into java/dev_acarb…
acarbonetto Feb 1, 2024
825c1f7
Fix merge
acarbonetto Feb 1, 2024
e3fa7fa
Apply more javadoc changes; minor review comments
acarbonetto Feb 1, 2024
5a96e65
Fix unit tests
acarbonetto Feb 1, 2024
9c0ab6c
Apply review comments
acarbonetto Feb 2, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
138 changes: 123 additions & 15 deletions java/client/src/main/java/glide/api/BaseClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,39 +2,36 @@
package glide.api;

import static glide.ffi.resolvers.SocketListenerResolver.getSocket;
import static glide.managers.RequestType.GET_STRING;
import static glide.managers.RequestType.PING;
import static glide.managers.RequestType.SET_STRING;

import glide.api.commands.ConnectionCommands;
import glide.api.commands.StringCommands;
import glide.api.models.commands.SetOptions;
import glide.api.models.configuration.BaseClientConfiguration;
import glide.api.models.exceptions.RedisException;
import glide.connectors.handlers.CallbackDispatcher;
import glide.connectors.handlers.ChannelHandler;
import glide.ffi.resolvers.RedisValueResolver;
import glide.managers.BaseCommandResponseResolver;
import glide.managers.CommandManager;
import glide.managers.ConnectionManager;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.BiFunction;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.ArrayUtils;
import response.ResponseOuterClass.Response;

/** Base Client class for Redis */
@AllArgsConstructor
public abstract class BaseClient implements AutoCloseable {
public abstract class BaseClient implements AutoCloseable, StringCommands, ConnectionCommands {

protected final ConnectionManager connectionManager;
protected final CommandManager commandManager;

/**
* Extracts the response from the Protobuf response and either throws an exception or returns the
* appropriate response as an Object
*
* @param response Redis protobuf message
* @return Response Object
*/
protected Object handleObjectResponse(Response response) {
// convert protobuf response into Object and then Object into T
return new BaseCommandResponseResolver(RedisValueResolver::valueFromPointer).apply(response);
}

/**
* Async request for an async (non-blocking) Redis client.
*
Expand Down Expand Up @@ -66,8 +63,8 @@ protected static <T> CompletableFuture<T> CreateClient(
* Closes this resource, relinquishing any underlying resources. This method is invoked
* automatically on objects managed by the try-with-resources statement.
*
* <p>see: <a
* href="https://docs.oracle.com/javase/8/docs/api/java/lang/AutoCloseable.html#close--">AutoCloseable::close()</a>
* @see <a
* href="https://docs.oracle.com/javase/8/docs/api/java/lang/AutoCloseable.html#close--">AutoCloseable::close()</a>
*/
@Override
public void close() throws ExecutionException {
Expand All @@ -91,4 +88,115 @@ protected static ConnectionManager buildConnectionManager(ChannelHandler channel
protected static CommandManager buildCommandManager(ChannelHandler channelHandler) {
return new CommandManager(channelHandler);
}

/**
* Extracts the response from the Protobuf response and either throws an exception or returns the
* appropriate response as an <code>Object</code>.
*
* @param response Redis protobuf message
* @return Response <code>Object</code>
*/
protected Object handleObjectResponse(Response response) {
// convert protobuf response into Object
return new BaseCommandResponseResolver(RedisValueResolver::valueFromPointer).apply(response);
}

/**
* Checks that the Response is empty.
*
* @return An empty response
*/
protected Void handleVoidResponse(Response response) {
Object value = handleObjectResponse(response);
if (value == null) {
return null;
}
throw new RedisException(
"Unexpected return type from Redis: got "
+ value.getClass().getSimpleName()
+ " expected null");
}

/**
* Extracts the response value from the Redis response and either throws an exception or returns
* the value as a <code>String</code>.
*
* @param response Redis protobuf message
* @return Response as a <code>String</code>
*/
protected String handleStringResponse(Response response) {
Object value = handleObjectResponse(response);
if (value instanceof String) {
return (String) value;
}
throw new RedisException(
"Unexpected return type from Redis: got "
+ value.getClass().getSimpleName()
+ " expected String");
}

/**
* Extracts the response value from the Redis response and either throws an exception or returns
* the value as an <code>Object[]</code>.
*
* @param response Redis protobuf message
* @return Response as an <code>Object[]</code>
*/
protected Object[] handleArrayResponse(Response response) {
Object value = handleObjectResponse(response);
if (value instanceof Object[]) {
return (Object[]) value;
}
throw new RedisException(
"Unexpected return type from Redis: got "
+ value.getClass().getSimpleName()
+ " expected Object[]");
}

/**
* Extracts the response value from the Redis response and either throws an exception or returns
* the value as a <code>Map</code>.
*
* @param response Redis protobuf message
* @return Response as a <code>Map</code>.
*/
@SuppressWarnings("unchecked")
protected Map<Object, Object> handleMapResponse(Response response) {
Object value = handleObjectResponse(response);
if (value instanceof Map) {
return (Map<Object, Object>) value;
}
throw new RedisException(
"Unexpected return type from Redis: got "
+ value.getClass().getSimpleName()
+ " expected Map");
}

@Override
public CompletableFuture<String> ping() {
return commandManager.submitNewCommand(PING, new String[0], this::handleStringResponse);
}

@Override
public CompletableFuture<String> ping(String msg) {
return commandManager.submitNewCommand(PING, new String[] {msg}, this::handleStringResponse);
}

@Override
public CompletableFuture<String> get(String key) {
return commandManager.submitNewCommand(
GET_STRING, new String[] {key}, this::handleStringResponse);
}

@Override
public CompletableFuture<Void> set(String key, String value) {
return commandManager.submitNewCommand(
SET_STRING, new String[] {key, value}, this::handleVoidResponse);
}

@Override
public CompletableFuture<String> set(String key, String value, SetOptions options) {
String[] arguments = ArrayUtils.addAll(new String[] {key, value}, options.toArgs());
return commandManager.submitNewCommand(SET_STRING, arguments, this::handleStringResponse);
}
}
50 changes: 43 additions & 7 deletions java/client/src/main/java/glide/api/RedisClient.java
Original file line number Diff line number Diff line change
@@ -1,18 +1,27 @@
/** Copyright GLIDE-for-Redis Project Contributors - SPDX Identifier: Apache-2.0 */
package glide.api;

import static glide.managers.RequestType.CUSTOM_COMMAND;
import static glide.managers.RequestType.INFO;

import glide.api.commands.BaseCommands;
import glide.api.commands.ConnectionCommands;
import glide.api.commands.ServerCommands;
import glide.api.models.Transaction;
import glide.api.models.commands.InfoOptions;
import glide.api.models.configuration.RedisClientConfiguration;
import glide.connectors.handlers.ChannelHandler;
import glide.managers.CommandManager;
import glide.managers.ConnectionManager;
import glide.managers.models.Command;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;

/**
* Async (non-blocking) client for Redis in Standalone mode. Use {@link #CreateClient} to request a
* client to Redis.
*/
public class RedisClient extends BaseClient implements BaseCommands {
public class RedisClient extends BaseClient
implements BaseCommands, ConnectionCommands, ServerCommands {

protected RedisClient(ConnectionManager connectionManager, CommandManager commandManager) {
super(connectionManager, commandManager);
Expand All @@ -22,16 +31,43 @@ protected RedisClient(ConnectionManager connectionManager, CommandManager comman
* Async request for an async (non-blocking) Redis client in Standalone mode.
*
* @param config Redis client Configuration
* @return a Future to connect and return a RedisClient
* @return A Future to connect and return a RedisClient
*/
public static CompletableFuture<RedisClient> CreateClient(RedisClientConfiguration config) {
return CreateClient(config, RedisClient::new);
try {
ChannelHandler channelHandler = buildChannelHandler();
ConnectionManager connectionManager = buildConnectionManager(channelHandler);
CommandManager commandManager = buildCommandManager(channelHandler);
// TODO: Support exception throwing, including interrupted exceptions
return connectionManager
.connectToRedis(config)
.thenApply(ignore -> new RedisClient(connectionManager, commandManager));
} catch (InterruptedException e) {
// Something bad happened while we were establishing netty connection to UDS
var future = new CompletableFuture<RedisClient>();
future.completeExceptionally(e);
return future;
}
}

@Override
public CompletableFuture<Object> customCommand(String[] args) {
Command command =
Command.builder().requestType(Command.RequestType.CUSTOM_COMMAND).arguments(args).build();
return commandManager.submitNewCommand(command, this::handleObjectResponse);
return commandManager.submitNewCommand(CUSTOM_COMMAND, args, this::handleStringResponse);
}

@Override
public CompletableFuture<Object[]> exec(Transaction transaction) {
return commandManager.submitNewCommand(
transaction, Optional.empty(), this::handleArrayResponse);
}

@Override
public CompletableFuture<String> info() {
return commandManager.submitNewCommand(INFO, new String[0], this::handleStringResponse);
}

@Override
public CompletableFuture<String> info(InfoOptions options) {
return commandManager.submitNewCommand(INFO, options.toArgs(), this::handleStringResponse);
}
}
95 changes: 80 additions & 15 deletions java/client/src/main/java/glide/api/RedisClusterClient.java
Original file line number Diff line number Diff line change
@@ -1,21 +1,29 @@
/** Copyright GLIDE-for-Redis Project Contributors - SPDX Identifier: Apache-2.0 */
package glide.api;

import static glide.managers.RequestType.CUSTOM_COMMAND;
import static glide.managers.RequestType.INFO;

import glide.api.commands.ClusterBaseCommands;
import glide.api.commands.ClusterServerCommands;
import glide.api.models.ClusterTransaction;
import glide.api.models.ClusterValue;
import glide.api.models.commands.InfoOptions;
import glide.api.models.configuration.RedisClusterClientConfiguration;
import glide.api.models.configuration.RequestRoutingConfiguration.Route;
import glide.connectors.handlers.ChannelHandler;
import glide.managers.CommandManager;
import glide.managers.ConnectionManager;
import glide.managers.models.Command;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;

/**
* Async (non-blocking) client for Redis in Cluster mode. Use {@link #CreateClient} to request a
* client to Redis.
*/
public class RedisClusterClient extends BaseClient implements ClusterBaseCommands {
public class RedisClusterClient extends BaseClient
implements ClusterBaseCommands, ClusterServerCommands {

protected RedisClusterClient(ConnectionManager connectionManager, CommandManager commandManager) {
super(connectionManager, commandManager);
Expand All @@ -25,37 +33,94 @@ protected RedisClusterClient(ConnectionManager connectionManager, CommandManager
* Async request for an async (non-blocking) Redis client in Cluster mode.
*
* @param config Redis cluster client Configuration
* @return a Future to connect and return a ClusterClient
* @return A Future to connect and return a RedisClusterClient
*/
public static CompletableFuture<RedisClusterClient> CreateClient(
RedisClusterClientConfiguration config) {
return CreateClient(config, RedisClusterClient::new);
try {
ChannelHandler channelHandler = buildChannelHandler();
ConnectionManager connectionManager = buildConnectionManager(channelHandler);
CommandManager commandManager = buildCommandManager(channelHandler);
// TODO: Support exception throwing, including interrupted exceptions
return connectionManager
.connectToRedis(config)
.thenApply(ignored -> new RedisClusterClient(connectionManager, commandManager));
} catch (InterruptedException e) {
// Something bad happened while we were establishing netty connection to UDS
var future = new CompletableFuture<RedisClusterClient>();
future.completeExceptionally(e);
return future;
}
}

@Override
public CompletableFuture<ClusterValue<Object>> customCommand(String[] args) {
Command command =
Command.builder().requestType(Command.RequestType.CUSTOM_COMMAND).arguments(args).build();
// TODO if a command returns a map as a single value, ClusterValue misleads user
return commandManager.submitNewCommand(
command, response -> ClusterValue.of(handleObjectResponse(response)));
CUSTOM_COMMAND,
args,
Optional.empty(),
response -> ClusterValue.of(handleObjectResponse(response)));
}

@Override
@SuppressWarnings("unchecked")
public CompletableFuture<ClusterValue<Object>> customCommand(String[] args, Route route) {
Command command =
Command.builder()
.requestType(Command.RequestType.CUSTOM_COMMAND)
.arguments(args)
.route(route)
.build();

return commandManager.submitNewCommand(
command,
CUSTOM_COMMAND,
args,
Optional.ofNullable(route),
response ->
route.isSingleNodeRoute()
? ClusterValue.ofSingleValue(handleObjectResponse(response))
: ClusterValue.ofMultiValue((Map<String, Object>) handleObjectResponse(response)));

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe you are not actually casting the keys in to strings with this (Map<String, Object>) , at runtime they will still remain as type Object not string. We may need to cast keys individually.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will test this and update the examples in the PR description.

}

@Override
public CompletableFuture<Object[]> exec(ClusterTransaction transaction) {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

need to test this:

  1. Is this a list of ClusterValue[], OR
  2. Is this a ClusterValue(Object[])

return commandManager.submitNewCommand(
transaction, Optional.empty(), this::handleArrayResponse);
}

@Override
public CompletableFuture<Object[]> exec(ClusterTransaction transaction, Route route) {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same

return commandManager.submitNewCommand(
transaction, Optional.ofNullable(route), this::handleArrayResponse);
}

@Override
public CompletableFuture<ClusterValue<String>> info() {
return commandManager.submitNewCommand(
INFO,
new String[0],
Optional.empty(),
response -> ClusterValue.of(handleStringResponse(response)));
}

@Override
public CompletableFuture<ClusterValue<String>> info(Route route) {
return commandManager.submitNewCommand(
INFO,
new String[0],
Optional.ofNullable(route),
response -> ClusterValue.of(handleStringResponse(response)));
}

@Override
public CompletableFuture<ClusterValue<String>> info(InfoOptions options) {
return commandManager.submitNewCommand(
INFO,
options.toArgs(),
Optional.empty(),
response -> ClusterValue.of(handleStringResponse(response)));
}

@Override
public CompletableFuture<ClusterValue<String>> info(InfoOptions options, Route route) {
return commandManager.submitNewCommand(
INFO,
options.toArgs(),
Optional.ofNullable(route),
response -> ClusterValue.of(handleStringResponse(response)));
}
}
Loading
Loading