Skip to content

Commit b52c268

Browse files
refactor: make request context a little nicer to use (#12)
1 parent 711ea65 commit b52c268

File tree

2 files changed

+19
-12
lines changed

2 files changed

+19
-12
lines changed

grpc-client-utils/src/main/java/org/hypertrace/core/grpcutils/client/GrpcClientRequestContextUtil.java

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
package org.hypertrace.core.grpcutils.client;
22

3-
import io.grpc.Context;
43
import java.util.Map;
54
import java.util.concurrent.Callable;
65
import javax.annotation.Nonnull;
@@ -40,15 +39,7 @@ public static void executeInTenantContext(String tenantId, Runnable r) {
4039
public static <V> V executeWithHeadersContext(@Nonnull Map<String, String> headers, @Nonnull Callable<V> c) {
4140
RequestContext requestContext = new RequestContext();
4241
headers.forEach(requestContext::add);
43-
44-
try {
45-
return Context.current().withValue(RequestContext.CURRENT, requestContext).call(c);
46-
} catch (Exception e) {
47-
if (e instanceof RuntimeException) {
48-
throw (RuntimeException)e;
49-
}
50-
throw new RuntimeException(e);
51-
}
42+
return requestContext.call(c);
5243
}
5344

5445
/**
@@ -60,7 +51,6 @@ public static <V> V executeWithHeadersContext(@Nonnull Map<String, String> heade
6051
public static void executeWithHeadersContext(@Nonnull Map<String, String> headers, @Nonnull Runnable r) {
6152
RequestContext requestContext = new RequestContext();
6253
headers.forEach(requestContext::add);
63-
64-
Context.current().withValue(RequestContext.CURRENT, requestContext).run(r);
54+
requestContext.run(r);
6555
}
6656
}

grpc-context-utils/src/main/java/org/hypertrace/core/grpcutils/context/RequestContext.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
import java.util.HashMap;
55
import java.util.Map;
66
import java.util.Optional;
7+
import java.util.concurrent.Callable;
8+
import javax.annotation.Nonnull;
79

810
/**
911
* Context of the GRPC request that should be carried and can made available to the services so that
@@ -41,4 +43,19 @@ public Optional<String> get(String headerKey) {
4143
public Map<String, String> getAll() {
4244
return Map.copyOf(headers);
4345
}
46+
47+
public <V> V call(@Nonnull Callable<V> callable) {
48+
try {
49+
return Context.current().withValue(RequestContext.CURRENT, this).call(callable);
50+
} catch (Exception e) {
51+
if (e instanceof RuntimeException) {
52+
throw (RuntimeException) e;
53+
}
54+
throw new RuntimeException(e);
55+
}
56+
}
57+
58+
public void run(@Nonnull Runnable runnable) {
59+
Context.current().withValue(RequestContext.CURRENT, this).run(runnable);
60+
}
4461
}

0 commit comments

Comments
 (0)