|
| 1 | +/* |
| 2 | + * Jooby https://jooby.io |
| 3 | + * Apache License Version 2.0 https://jooby.io/LICENSE.txt |
| 4 | + * Copyright 2014 Edgar Espina |
| 5 | + */ |
| 6 | +package io.jooby.internal.jsonrpc; |
| 7 | + |
| 8 | +import java.util.Map; |
| 9 | +import java.util.Optional; |
| 10 | + |
| 11 | +import org.jspecify.annotations.NonNull; |
| 12 | +import org.slf4j.Logger; |
| 13 | + |
| 14 | +import io.jooby.Context; |
| 15 | +import io.jooby.Reified; |
| 16 | +import io.jooby.SneakyThrows; |
| 17 | +import io.jooby.jsonrpc.*; |
| 18 | + |
| 19 | +/** |
| 20 | + * The internal execution engine and "final invoker" for JSON-RPC requests. |
| 21 | + * |
| 22 | + * <p>This class acts as the terminal end of the {@link JsonRpcChain}. It is responsible for the |
| 23 | + * final stages of the JSON-RPC lifecycle: |
| 24 | + * |
| 25 | + * <ul> |
| 26 | + * <li>Validating the parsed request envelope. |
| 27 | + * <li>Routing the request to the appropriate {@link JsonRpcService}. |
| 28 | + * <li>Executing the target method. |
| 29 | + * <li>Acting as the ultimate safety net by catching all exceptions and translating them into |
| 30 | + * compliant {@link JsonRpcResponse} objects. |
| 31 | + * </ul> |
| 32 | + */ |
| 33 | +public class JsonRpcExecutor implements JsonRpcChain { |
| 34 | + private final Map<String, JsonRpcService> services; |
| 35 | + private final Map<Class<?>, Logger> loggers; |
| 36 | + private final Exception parseError; |
| 37 | + |
| 38 | + /** |
| 39 | + * Constructs a new executor for a single JSON-RPC request. |
| 40 | + * |
| 41 | + * @param services A map of registered JSON-RPC services keyed by method name. |
| 42 | + * @param loggers A map of service loggers keyed by service class. |
| 43 | + * @param parseError Any exception that occurred during the initial JSON parsing phase. |
| 44 | + */ |
| 45 | + public JsonRpcExecutor( |
| 46 | + Map<String, JsonRpcService> services, Map<Class<?>, Logger> loggers, Exception parseError) { |
| 47 | + this.services = services; |
| 48 | + this.loggers = loggers; |
| 49 | + this.parseError = parseError; |
| 50 | + } |
| 51 | + |
| 52 | + /** |
| 53 | + * Executes the JSON-RPC request and returns an optional response. |
| 54 | + * |
| 55 | + * <p>This method adheres strictly to the JSON-RPC 2.0 specification regarding error handling and |
| 56 | + * response generation. It will return {@link Optional#empty()} for Notifications, unless a |
| 57 | + * fundamental Parse Error or Invalid Request error occurs, which always require a response. |
| 58 | + * |
| 59 | + * @param ctx The current HTTP context passed down the chain. |
| 60 | + * @param request The incoming JSON-RPC request passed down the chain. |
| 61 | + * @return An Optional containing the JSON-RPC response, or empty if the request was a valid |
| 62 | + * Notification. |
| 63 | + */ |
| 64 | + @Override |
| 65 | + public @NonNull Optional<JsonRpcResponse> proceed( |
| 66 | + @NonNull Context ctx, @NonNull JsonRpcRequest request) { |
| 67 | + var log = loggers.get(JsonRpcService.class); |
| 68 | + try { |
| 69 | + if (parseError != null) { |
| 70 | + throw new JsonRpcException(JsonRpcErrorCode.PARSE_ERROR, parseError); |
| 71 | + } |
| 72 | + if (!request.isValid()) { |
| 73 | + throw new JsonRpcException(JsonRpcErrorCode.INVALID_REQUEST, "Invalid JSON-RPC request"); |
| 74 | + } |
| 75 | + var fullMethod = request.getMethod(); |
| 76 | + var targetService = services.get(fullMethod); |
| 77 | + if (targetService != null) { |
| 78 | + log = loggers.get(targetService.getClass()); |
| 79 | + var result = targetService.execute(ctx, request); |
| 80 | + return request.getId() != null |
| 81 | + ? Optional.of(JsonRpcResponse.success(request.getId(), result)) |
| 82 | + : Optional.empty(); |
| 83 | + } |
| 84 | + if (request.getId() == null) { |
| 85 | + return Optional.empty(); |
| 86 | + } |
| 87 | + throw new JsonRpcException( |
| 88 | + JsonRpcErrorCode.METHOD_NOT_FOUND, "Method not found: " + fullMethod); |
| 89 | + } catch (Throwable cause) { |
| 90 | + return toRpcResponse(ctx, log, request, cause); |
| 91 | + } |
| 92 | + } |
| 93 | + |
| 94 | + private Optional<JsonRpcResponse> toRpcResponse( |
| 95 | + Context ctx, Logger log, JsonRpcRequest request, Throwable ex) { |
| 96 | + var code = toErrorCode(ctx, ex); |
| 97 | + log(log, request, code, ex); |
| 98 | + |
| 99 | + if (SneakyThrows.isFatal(ex)) { |
| 100 | + throw SneakyThrows.propagate(ex); |
| 101 | + } else if (ex.getCause() != null && SneakyThrows.isFatal(ex.getCause())) { |
| 102 | + throw SneakyThrows.propagate(ex.getCause()); |
| 103 | + } |
| 104 | + |
| 105 | + if (request.getId() != null) { |
| 106 | + return Optional.of(JsonRpcResponse.error(request.getId(), code, ex)); |
| 107 | + } else if (code == JsonRpcErrorCode.PARSE_ERROR || code == JsonRpcErrorCode.INVALID_REQUEST) { |
| 108 | + // must return a valid response even if the request is invalid |
| 109 | + return Optional.of(JsonRpcResponse.error(null, code, ex)); |
| 110 | + } |
| 111 | + return Optional.empty(); |
| 112 | + } |
| 113 | + |
| 114 | + /** |
| 115 | + * Logs JSON-RPC errors adaptively based on the error code. |
| 116 | + * |
| 117 | + * <p>Internal server errors are logged as standard errors. Authorization and routing errors are |
| 118 | + * logged at debug level to prevent log flooding. Other application errors are logged as warnings. |
| 119 | + * |
| 120 | + * @param log The logger instance to use. |
| 121 | + * @param request The request that triggered the error. |
| 122 | + * @param code The error code. |
| 123 | + * @param cause The underlying exception. |
| 124 | + */ |
| 125 | + private void log(Logger log, JsonRpcRequest request, JsonRpcErrorCode code, Throwable cause) { |
| 126 | + var type = code == JsonRpcErrorCode.INTERNAL_ERROR ? "server" : "client"; |
| 127 | + var message = "JSON-RPC {} error [{} {}] on method '{}' (id: {})"; |
| 128 | + switch (code) { |
| 129 | + case INTERNAL_ERROR -> |
| 130 | + log.error( |
| 131 | + message, |
| 132 | + type, |
| 133 | + code.getCode(), |
| 134 | + code.getMessage(), |
| 135 | + request.getMethod(), |
| 136 | + request.getId(), |
| 137 | + cause); |
| 138 | + case UNAUTHORIZED, FORBIDDEN, NOT_FOUND_ERROR -> |
| 139 | + log.debug( |
| 140 | + message, |
| 141 | + type, |
| 142 | + code.getCode(), |
| 143 | + code.getMessage(), |
| 144 | + request.getMethod(), |
| 145 | + request.getId(), |
| 146 | + cause); |
| 147 | + default -> { |
| 148 | + if (cause instanceof JsonRpcException) { |
| 149 | + log.warn( |
| 150 | + message, |
| 151 | + type, |
| 152 | + code.getCode(), |
| 153 | + code.getMessage(), |
| 154 | + request.getMethod(), |
| 155 | + request.getId()); |
| 156 | + } else { |
| 157 | + log.warn( |
| 158 | + message, |
| 159 | + type, |
| 160 | + code.getCode(), |
| 161 | + code.getMessage(), |
| 162 | + request.getMethod(), |
| 163 | + request.getId(), |
| 164 | + cause); |
| 165 | + } |
| 166 | + } |
| 167 | + } |
| 168 | + } |
| 169 | + |
| 170 | + public JsonRpcErrorCode toErrorCode(Context ctx, Throwable cause) { |
| 171 | + if (cause instanceof JsonRpcException rpcException) { |
| 172 | + return rpcException.getCode(); |
| 173 | + } |
| 174 | + // Attempt to look up any user-defined exception mappings from the registry |
| 175 | + Map<Class<?>, JsonRpcErrorCode> customErrorMapping = |
| 176 | + ctx.require(Reified.map(Class.class, JsonRpcErrorCode.class)); |
| 177 | + return customErrorMapping.entrySet().stream() |
| 178 | + .filter(entry -> entry.getKey().isInstance(cause)) |
| 179 | + .findFirst() |
| 180 | + .map(Map.Entry::getValue) |
| 181 | + .orElseGet(() -> JsonRpcErrorCode.of(ctx.getRouter().errorCode(cause))); |
| 182 | + } |
| 183 | +} |
0 commit comments