Skip to content

Commit cd012e1

Browse files
committed
fix(jsonrpc): normalize error responses and fatal handling
Replace jsonrpc4j's unhandled -32001 fallback with a fixed -32603 response so unmapped exception types and raw messages no longer reach clients. Keep the documented -32001 contract for net_version and eth_chainId through explicit mappings with fixed message and data. Propagate VirtualMachineError, ThreadDeath, LinkageError, and TronError through the JSON-RPC boundary. Scan complete cause chains without allocating a visited set, detecting cycles without missing fatal causes. Classify Throwables escaping dispatch before logging or mapping them. Before rethrowing an Error, unwrap response decorators with a bounded walk and make a best-effort attempt to commit an empty HTTP 500 on the underlying response. Preserve the original error if cleanup fails, and abandon cleanup without delegating into cyclic or unresolved wrappers. Route single requests through handleRequest because the servlet handle API catches Throwable. Catch RuntimeException, IOException, and Error at both dispatch boundaries, then propagate a classified fatal cause or return -32603 when a response is appropriate. This also covers non-fatal Errors from interceptor hooks. Discard partial dispatch output on failure. Recover each failed batch element without discarding earlier results or skipping later requests. Share internal-error construction across serialization, dispatch, and response-parsing failures. Count only the replacement when parsing fails, retaining existing overflow rules and the current single/batch handling of requests without an id. Bound unmapped-exception and chain-identity failure logging to the first occurrence per operation and exception type. Classify fatal causes before logging chain-identity and asynchronous log-query failures. Log the first escaped dispatch failure in each batch at ERROR with its cause; repeats use DEBUG with only the index and exception type. Restore interrupted status for asynchronous log queries. Reject Boolean, object, and array request IDs before dispatch with -32600 and id:null. Reject non-null scalar params with -32600, preserve valid IDs, and isolate invalid batch elements so their siblings run. Missing, null, array, and object params keep their existing semantics. Remove the obsolete request replay wrapper and HTTP status provider. Add resolver, servlet, embedded-Jetty, chain-identity, asynchronous failure, dispatch-contract, and request-envelope regression coverage. Exercise the real HTTP interceptor chain and observe commitment without performing it on the servlet's behalf. Test interceptor Errors with a real server and preserve the existing notification response-suppression rules with characterization tests. Add a package-private server injection seam for servlet tests without changing production initialization.
1 parent 0d19485 commit cd012e1

14 files changed

Lines changed: 3232 additions & 320 deletions

‎framework/src/main/java/org/tron/core/services/filter/CachedBodyRequestWrapper.java‎

Lines changed: 0 additions & 97 deletions
This file was deleted.
Lines changed: 122 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,161 @@
11
package org.tron.core.services.jsonrpc;
22

33
import com.fasterxml.jackson.databind.JsonNode;
4-
import com.googlecode.jsonrpc4j.ErrorData;
54
import com.googlecode.jsonrpc4j.ErrorResolver;
65
import com.googlecode.jsonrpc4j.JsonRpcError;
76
import com.googlecode.jsonrpc4j.JsonRpcErrors;
7+
import com.googlecode.jsonrpc4j.ProxyUtil;
88
import com.googlecode.jsonrpc4j.ReflectionUtil;
99
import java.lang.reflect.Method;
1010
import java.util.List;
11+
import java.util.Set;
12+
import java.util.concurrent.ConcurrentHashMap;
13+
import lombok.extern.slf4j.Slf4j;
14+
import org.apache.commons.lang3.StringUtils;
15+
import org.tron.core.exception.TronError;
1116
import org.tron.core.exception.jsonrpc.JsonRpcException;
1217

1318
/**
1419
* {@link ErrorResolver} that uses annotations.
1520
*/
21+
@Slf4j(topic = "API")
1622
public enum JsonRpcErrorResolver implements ErrorResolver {
1723
INSTANCE;
1824

25+
private static final Set<String> SEEN_FAILURES = ConcurrentHashMap.newKeySet();
26+
1927
/**
2028
* {@inheritDoc}
2129
*/
2230
@Override
2331
public JsonError resolveError(
2432
Throwable thrownException, Method method, List<JsonNode> arguments) {
25-
JsonRpcError resolver = getResolverForException(thrownException, method);
26-
if (notFoundResolver(resolver)) {
27-
return null;
33+
Error fatal = findFatalCause(thrownException);
34+
if (fatal != null) {
35+
throw fatal;
36+
}
37+
38+
JsonRpcError resolver = method == null
39+
? null : getResolverForException(thrownException, method);
40+
if (resolver == null) {
41+
logUnhandledException(method, thrownException);
42+
return new JsonError(JsonError.INTERNAL_ERROR.code, "Internal error", null);
2843
}
2944

3045
String message = hasErrorMessage(resolver) ? resolver.message() : thrownException.getMessage();
46+
if (StringUtils.isBlank(message)) {
47+
message = defaultMessageFor(resolver.code());
48+
}
3149

32-
// data priority: exception > annotation > default ErrorData
50+
// data priority: exception > annotation
3351
Object data = null;
3452
if (thrownException instanceof JsonRpcException) {
3553
JsonRpcException jsonRpcException = (JsonRpcException) thrownException;
3654
data = jsonRpcException.getData();
3755
}
3856

39-
if (data == null) {
40-
data = hasErrorData(resolver)
41-
? resolver.data()
42-
: new ErrorData(resolver.exception().getName(), message);
57+
if (data == null && hasErrorData(resolver)) {
58+
data = resolver.data();
4359
}
44-
60+
4561
return new JsonError(resolver.code(), message, data);
4662
}
4763

64+
/**
65+
* Returns the first {@link VirtualMachineError}, {@link ThreadDeath}, {@link LinkageError} or
66+
* {@link TronError} found in {@code throwable} or its cause chain, or {@code null} if there is
67+
* none.
68+
*
69+
* <p>This is the JSON-RPC layer's propagation policy for fatal causes, not a statement that
70+
* other {@link Error}s are safe to recover from. Callers should apply it before any logging so a
71+
* fatal cause is never recorded as an ordinary failure. The scan has no depth cutoff, terminates
72+
* on cyclic cause chains, and uses neither recursion nor auxiliary collections.
73+
*/
74+
public static Error findFatalCause(Throwable throwable) {
75+
// Avoid allocations when handling memory exhaustion, without truncating deep cause chains.
76+
// Check both fast-pointer steps so cycle detection cannot skip a fatal cause inside a cycle.
77+
Throwable slow = throwable;
78+
Throwable fast = throwable;
79+
while (fast != null) {
80+
if (isFatal(fast)) {
81+
return (Error) fast;
82+
}
83+
fast = fast.getCause();
84+
if (fast == null) {
85+
return null;
86+
}
87+
if (isFatal(fast)) {
88+
return (Error) fast;
89+
}
90+
fast = fast.getCause();
91+
slow = slow.getCause();
92+
if (fast == slow) {
93+
return null;
94+
}
95+
}
96+
return null;
97+
}
98+
99+
private static boolean isFatal(Throwable cause) {
100+
return cause instanceof VirtualMachineError
101+
|| cause instanceof ThreadDeath
102+
|| cause instanceof LinkageError
103+
|| cause instanceof TronError;
104+
}
105+
106+
/**
107+
* Returns true the first time a failure of this exception type is seen for the operation.
108+
* Callers log the first occurrence with the Throwable and later ones without it.
109+
*
110+
* <p>The record is static and shared by all callers of this method, currently the resolver's
111+
* unhandled-exception log and chain-identity lookups. It is deduplication rather than a
112+
* time-window rate limit: entries are never evicted or reset in production, so a failure that
113+
* recurs after a recovery is not logged at WARN again.
114+
*/
115+
static boolean firstOccurrence(String operation, Throwable failure) {
116+
return SEEN_FAILURES.add(operation + '\0' + failure.getClass().getName());
117+
}
118+
119+
private static void logUnhandledException(Method method, Throwable thrownException) {
120+
String methodName = rpcMethodName(method);
121+
if (firstOccurrence(methodName, thrownException)) {
122+
// The first occurrence retains the Throwable for diagnosis. Repeated failures omit both
123+
// the stack and exception message so a request loop cannot flood the WARN log.
124+
logger.warn("Unhandled exception in JSON-RPC method {}", methodName, thrownException);
125+
} else {
126+
logger.debug("Repeated unhandled exception in JSON-RPC method {} ({})",
127+
methodName, thrownException.getClass().getName());
128+
}
129+
}
130+
131+
static void clearSeenFailuresForTest() {
132+
SEEN_FAILURES.clear();
133+
}
134+
135+
private static String rpcMethodName(Method method) {
136+
if (method == null) {
137+
return "unknown";
138+
}
139+
try {
140+
return ProxyUtil.getMethodName(method);
141+
} catch (RuntimeException e) {
142+
return method.getName();
143+
}
144+
}
145+
146+
private static String defaultMessageFor(int code) {
147+
switch (code) {
148+
case -32600:
149+
return "Invalid Request";
150+
case -32601:
151+
return "Method not found";
152+
case -32602:
153+
return "Invalid params";
154+
default:
155+
return "Internal error";
156+
}
157+
}
158+
48159
private JsonRpcError getResolverForException(Throwable thrownException, Method method) {
49160
JsonRpcErrors errors = ReflectionUtil.getAnnotation(method, JsonRpcErrors.class);
50161
if (hasAnnotations(errors)) {
@@ -57,10 +168,6 @@ private JsonRpcError getResolverForException(Throwable thrownException, Method m
57168
return null;
58169
}
59170

60-
private boolean notFoundResolver(JsonRpcError resolver) {
61-
return resolver == null;
62-
}
63-
64171
private boolean hasErrorMessage(JsonRpcError em) {
65172
// noinspection ConstantConditions
66173
return em.message() != null && !em.message().trim().isEmpty();
@@ -78,4 +185,4 @@ private boolean hasAnnotations(JsonRpcErrors errors) {
78185
private boolean isExceptionInstanceOfError(Throwable target, JsonRpcError em) {
79186
return em.exception().isInstance(target);
80187
}
81-
}
188+
}

0 commit comments

Comments
 (0)