Implement jsonRpc command

Co-authored-by: technillogue <technillogue@gmail.com>

Closes #668
This commit is contained in:
AsamK 2021-08-09 17:42:01 +02:00
parent 6c00054407
commit a8bbdb54d0
20 changed files with 863 additions and 31 deletions

View file

@ -0,0 +1,18 @@
package org.asamk.signal.jsonrpc;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.List;
public class JsonRpcBulkMessage extends JsonRpcMessage {
List<JsonNode> messages;
public JsonRpcBulkMessage(final List<JsonNode> messages) {
this.messages = messages;
}
public List<JsonNode> getMessages() {
return messages;
}
}

View file

@ -0,0 +1,14 @@
package org.asamk.signal.jsonrpc;
public class JsonRpcException extends Exception {
private final JsonRpcResponse.Error error;
public JsonRpcException(final JsonRpcResponse.Error error) {
this.error = error;
}
public JsonRpcResponse.Error getError() {
return error;
}
}

View file

@ -0,0 +1,9 @@
package org.asamk.signal.jsonrpc;
/**
* Represents a JSON-RPC (bulk) request or (bulk) response.
* https://www.jsonrpc.org/specification
*/
public abstract class JsonRpcMessage {
}

View file

@ -0,0 +1,216 @@
package org.asamk.signal.jsonrpc;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ContainerNode;
import com.fasterxml.jackson.databind.node.ValueNode;
import org.asamk.signal.util.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
public class JsonRpcReader {
private final static Logger logger = LoggerFactory.getLogger(JsonRpcReader.class);
private final JsonRpcSender jsonRpcSender;
private final ObjectMapper objectMapper;
private final Supplier<String> lineSupplier;
public JsonRpcReader(
final JsonRpcSender jsonRpcSender, final Supplier<String> lineSupplier
) {
this.jsonRpcSender = jsonRpcSender;
this.lineSupplier = lineSupplier;
this.objectMapper = Util.createJsonObjectMapper();
}
public void readRequests(
final RequestHandler requestHandler, final Consumer<JsonRpcResponse> responseHandler
) {
while (!Thread.interrupted()) {
JsonRpcMessage message = readMessage();
if (message == null) break;
if (message instanceof JsonRpcRequest) {
final var response = handleRequest(requestHandler, (JsonRpcRequest) message);
if (response != null) {
jsonRpcSender.sendResponse(response);
}
} else if (message instanceof JsonRpcResponse) {
responseHandler.accept((JsonRpcResponse) message);
} else {
final var responseList = ((JsonRpcBulkMessage) message).getMessages().stream().map(jsonNode -> {
final JsonRpcRequest request;
try {
request = parseJsonRpcRequest(jsonNode);
} catch (JsonRpcException e) {
return JsonRpcResponse.forError(e.getError(), getId(jsonNode));
}
return handleRequest(requestHandler, request);
}).filter(Objects::nonNull).collect(Collectors.toList());
jsonRpcSender.sendBulkResponses(responseList);
}
}
}
private JsonRpcResponse handleRequest(final RequestHandler requestHandler, final JsonRpcRequest request) {
try {
final var result = requestHandler.apply(request.getMethod(), request.getParams());
if (request.getId() != null) {
return JsonRpcResponse.forSuccess(result, request.getId());
}
} catch (JsonRpcException e) {
if (request.getId() != null) {
return JsonRpcResponse.forError(e.getError(), request.getId());
}
}
return null;
}
private JsonRpcMessage readMessage() {
while (!Thread.interrupted()) {
String input = lineSupplier.get();
if (input == null) {
// Reached end of input stream
break;
}
JsonRpcMessage message = parseJsonRpcMessage(input);
if (message == null) continue;
return message;
}
return null;
}
private JsonRpcMessage parseJsonRpcMessage(final String input) {
final JsonNode jsonNode;
try {
jsonNode = objectMapper.readTree(input);
} catch (JsonParseException e) {
jsonRpcSender.sendResponse(JsonRpcResponse.forError(new JsonRpcResponse.Error(JsonRpcResponse.Error.PARSE_ERROR,
e.getMessage(),
null), null));
return null;
} catch (IOException e) {
throw new AssertionError(e);
}
if (jsonNode == null) {
jsonRpcSender.sendResponse(JsonRpcResponse.forError(new JsonRpcResponse.Error(JsonRpcResponse.Error.INVALID_REQUEST,
"invalid request",
null), null));
return null;
} else if (jsonNode.isArray()) {
if (jsonNode.size() == 0) {
jsonRpcSender.sendResponse(JsonRpcResponse.forError(new JsonRpcResponse.Error(JsonRpcResponse.Error.INVALID_REQUEST,
"invalid request",
null), null));
return null;
}
return new JsonRpcBulkMessage(StreamSupport.stream(jsonNode.spliterator(), false)
.collect(Collectors.toList()));
} else if (jsonNode.isObject()) {
if (jsonNode.has("result") || jsonNode.has("error")) {
return parseJsonRpcResponse(jsonNode);
} else {
try {
return parseJsonRpcRequest(jsonNode);
} catch (JsonRpcException e) {
jsonRpcSender.sendResponse(JsonRpcResponse.forError(e.getError(), getId(jsonNode)));
return null;
}
}
} else {
jsonRpcSender.sendResponse(JsonRpcResponse.forError(new JsonRpcResponse.Error(JsonRpcResponse.Error.INVALID_REQUEST,
"unexpected type: " + jsonNode.getNodeType().name(),
null), null));
return null;
}
}
private ValueNode getId(JsonNode jsonNode) {
final var id = jsonNode.get("id");
return id instanceof ValueNode ? (ValueNode) id : null;
}
private JsonRpcRequest parseJsonRpcRequest(final JsonNode input) throws JsonRpcException {
JsonRpcRequest request;
try {
request = objectMapper.treeToValue(input, JsonRpcRequest.class);
} catch (JsonMappingException e) {
throw new JsonRpcException(new JsonRpcResponse.Error(JsonRpcResponse.Error.INVALID_REQUEST,
e.getMessage(),
null));
} catch (IOException e) {
throw new AssertionError(e);
}
if (!"2.0".equals(request.getJsonrpc())) {
throw new JsonRpcException(new JsonRpcResponse.Error(JsonRpcResponse.Error.INVALID_REQUEST,
"only jsonrpc version 2.0 is supported",
null));
}
if (request.getMethod() == null) {
throw new JsonRpcException(new JsonRpcResponse.Error(JsonRpcResponse.Error.INVALID_REQUEST,
"method field must be set",
null));
}
return request;
}
private JsonRpcResponse parseJsonRpcResponse(final JsonNode input) {
JsonRpcResponse response;
try {
response = objectMapper.treeToValue(input, JsonRpcResponse.class);
} catch (JsonParseException | JsonMappingException e) {
logger.debug("Received invalid jsonrpc response {}", e.getMessage());
return null;
} catch (IOException e) {
throw new AssertionError(e);
}
if (!"2.0".equals(response.getJsonrpc())) {
logger.debug("Received invalid jsonrpc response with invalid version {}", response.getJsonrpc());
return null;
}
if (response.getResult() != null && response.getError() != null) {
logger.debug("Received invalid jsonrpc response with both result and error");
return null;
}
if (response.getResult() == null && response.getError() == null) {
logger.debug("Received invalid jsonrpc response without result and error");
return null;
}
if (response.getId() == null || response.getId().isNull()) {
logger.debug("Received invalid jsonrpc response without id");
return null;
}
return response;
}
public interface RequestHandler {
JsonNode apply(String method, ContainerNode<?> params) throws JsonRpcException;
}
}

View file

@ -0,0 +1,73 @@
package org.asamk.signal.jsonrpc;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.node.ContainerNode;
import com.fasterxml.jackson.databind.node.ValueNode;
/**
* Represents a JSON-RPC request.
* https://www.jsonrpc.org/specification#request_object
*/
public class JsonRpcRequest extends JsonRpcMessage {
/**
* A String specifying the version of the JSON-RPC protocol. MUST be exactly "2.0".
*/
String jsonrpc;
/**
* A String containing the name of the method to be invoked.
* Method names that begin with the word rpc followed by a period character (U+002E or ASCII 46)
* are reserved for rpc-internal methods and extensions and MUST NOT be used for anything else.
*/
String method;
/**
* A Structured value that holds the parameter values to be used during the invocation of the method.
* This member MAY be omitted.
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
ContainerNode<?> params;
/**
* An identifier established by the Client that MUST contain a String, Number, or NULL value if included.
* If it is not included it is assumed to be a notification.
* The value SHOULD normally not be Null and Numbers SHOULD NOT contain fractional parts
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
ValueNode id;
public static JsonRpcRequest forNotification(
final String method, final ContainerNode<?> params, final ValueNode id
) {
return new JsonRpcRequest("2.0", method, params, id);
}
private JsonRpcRequest() {
}
private JsonRpcRequest(
final String jsonrpc, final String method, final ContainerNode<?> params, final ValueNode id
) {
this.jsonrpc = jsonrpc;
this.method = method;
this.params = params;
this.id = id;
}
public String getJsonrpc() {
return jsonrpc;
}
public String getMethod() {
return method;
}
public ContainerNode<?> getParams() {
return params;
}
public ValueNode getId() {
return id;
}
}

View file

@ -0,0 +1,120 @@
package org.asamk.signal.jsonrpc;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ValueNode;
/**
* Represents a JSON-RPC response.
* https://www.jsonrpc.org/specification#response_object
*/
public class JsonRpcResponse extends JsonRpcMessage {
/**
* A String specifying the version of the JSON-RPC protocol. MUST be exactly "2.0".
*/
String jsonrpc;
/**
* This member is REQUIRED on success.
* This member MUST NOT exist if there was an error invoking the method.
* The value of this member is determined by the method invoked on the Server.
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
JsonNode result;
/**
* This member is REQUIRED on error.
* This member MUST NOT exist if there was no error triggered during invocation.
* The value for this member MUST be an Object as defined in section 5.1.
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
Error error;
/**
* This member is REQUIRED.
* It MUST be the same as the value of the id member in the Request Object.
* If there was an error in detecting the id in the Request object (e.g. Parse error/Invalid Request), it MUST be Null.
*/
ValueNode id;
public static JsonRpcResponse forSuccess(JsonNode result, ValueNode id) {
return new JsonRpcResponse("2.0", result, null, id);
}
public static JsonRpcResponse forError(Error error, ValueNode id) {
return new JsonRpcResponse("2.0", null, error, id);
}
private JsonRpcResponse() {
}
private JsonRpcResponse(final String jsonrpc, final JsonNode result, final Error error, final ValueNode id) {
this.jsonrpc = jsonrpc;
this.result = result;
this.error = error;
this.id = id;
}
public String getJsonrpc() {
return jsonrpc;
}
public JsonNode getResult() {
return result;
}
public Error getError() {
return error;
}
public ValueNode getId() {
return id;
}
public static class Error {
public static final int PARSE_ERROR = -32700;
public static final int INVALID_REQUEST = -32600;
public static final int METHOD_NOT_FOUND = -32601;
public static final int INVALID_PARAMS = -32602;
public static final int INTERNAL_ERROR = -32603;
/**
* A Number that indicates the error type that occurred.
* This MUST be an integer.
*/
int code;
/**
* A String providing a short description of the error.
* The message SHOULD be limited to a concise single sentence.
*/
String message;
/**
* A Primitive or Structured value that contains additional information about the error.
* This may be omitted.
* The value of this member is defined by the Server (e.g. detailed error information, nested errors etc.).
*/
JsonNode data;
public Error(final int code, final String message, final JsonNode data) {
this.code = code;
this.message = message;
this.data = data;
}
public int getCode() {
return code;
}
public String getMessage() {
return message;
}
public JsonNode getData() {
return data;
}
}
}

View file

@ -0,0 +1,30 @@
package org.asamk.signal.jsonrpc;
import org.asamk.signal.JsonWriter;
import java.util.List;
public class JsonRpcSender {
private final JsonWriter jsonWriter;
public JsonRpcSender(final JsonWriter jsonWriter) {
this.jsonWriter = jsonWriter;
}
public void sendRequest(JsonRpcRequest request) {
jsonWriter.write(request);
}
public void sendBulkRequests(List<JsonRpcRequest> requests) {
jsonWriter.write(requests);
}
public void sendResponse(JsonRpcResponse response) {
jsonWriter.write(response);
}
public void sendBulkResponses(List<JsonRpcResponse> responses) {
jsonWriter.write(responses);
}
}