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

fix the triple header context transfer issue #1467

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -62,14 +62,8 @@ public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<Re
SofaResponse sofaResponse = new SofaResponse();
final Throwable[] throwable = { null };
SofaRequest sofaRequest = new SofaRequest();
TripleTracerAdapter.serverReceived(sofaRequest, serverServiceDefinition, call, requestHeaders);
SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext();
SofaTracerSpan serverSpan = sofaTraceContext.getCurrentSpan();

Context ctxWithSpan = Context.current()
.withValue(TracingContextKey.getKey(), serverSpan)
.withValue(TracingContextKey.getSpanContextKey(), serverSpan.context())
.withValue(TracingContextKey.getKeySofaRequest(), sofaRequest);
Context ctxWithSpan = convertHeaderToContext(call, requestHeaders, sofaRequest, serverServiceDefinition);

//这里和下面不在一个线程
if (RpcRunningState.isDebugMode()) {
Expand Down Expand Up @@ -167,4 +161,19 @@ private StatusRuntimeException fromThrowable(Throwable t) {
};
return result;
}

protected <ReqT, RespT> Context convertHeaderToContext(ServerCall<ReqT, RespT> call,
Metadata requestHeaders, SofaRequest sofaRequest,
ServerServiceDefinition serverServiceDefinition) {
TripleTracerAdapter.serverReceived(sofaRequest, serverServiceDefinition, call, requestHeaders);
String userId = TripleTracerAdapter.getUserId(requestHeaders);
SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext();
SofaTracerSpan serverSpan = sofaTraceContext.getCurrentSpan();
return Context.current()
.withValue(TracingContextKey.getKey(), serverSpan)
.withValue(TracingContextKey.getSpanContextKey(), serverSpan.context())
.withValue(TracingContextKey.getKeySofaRequest(), sofaRequest)
.withValue(TracingContextKey.getKeyMetadata(), requestHeaders)
.withValue(TracingContextKey.getKeyUserId(), userId);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ public class TracingContextKey {
public static final String KEY_SOFA_REQUEST_NAME = "io.opentracing.sofa-request";
private static final Context.Key<SofaRequest> keySofaRequest = Context.key(KEY_SOFA_REQUEST_NAME);
private static final Context.Key<Metadata> keyMetadata = Context.key("io.opentracing.metadata");
public static final String KEY_TRIPLE_USER_ID = "io.opentracing.tri-user-id";
private static final Context.Key<String> keyUserId = Context.key(KEY_TRIPLE_USER_ID);

/**
* Retrieves the active span.
Expand Down Expand Up @@ -70,4 +72,8 @@ public static Context.Key<SofaRequest> getKeySofaRequest() {
public static Context.Key<Metadata> getKeyMetadata() {
return keyMetadata;
}

public static Context.Key<String> getKeyUserId() {
return keyUserId;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
*/
package com.alipay.sofa.rpc.tracer.sofatracer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alipay.common.tracer.core.appender.self.SelfLog;
import com.alipay.common.tracer.core.context.span.SofaTracerSpanContext;
import com.alipay.common.tracer.core.context.trace.SofaTraceContext;
Expand Down Expand Up @@ -51,6 +53,7 @@
import java.util.Set;

import static com.alipay.sofa.rpc.common.RemotingConstants.HEAD_APP_NAME;
import static com.alipay.sofa.rpc.server.triple.TripleHeadKeys.HEAD_KEY_UNIT_INFO;

/**
* 客户端:startRpc ——&gt; filter --&gt; beforeSend --&gt; 存入tracer信息 --&gt; clientReceived
Expand Down Expand Up @@ -114,7 +117,7 @@ public static void beforeSend(SofaRequest sofaRequest, ConsumerConfig consumerCo
if (StringUtils.isNotBlank(route)) {
Map<String, String> map = new HashMap<>();
map.put(USERID_KEY, route);
header.put(TripleHeadKeys.HEAD_KEY_UNIT_INFO.name(), JSONUtils.toJSONString(map));
header.put(HEAD_KEY_UNIT_INFO.name(), JSONUtils.toJSONString(map));
}

if (StringUtils.isNotEmpty(consumerConfig.getUniqueId())) {
Expand Down Expand Up @@ -300,4 +303,15 @@ public static void serverSend(SofaRequest request, final Metadata requestHeaders
EventBus.post(new ServerSendEvent(request, response, throwable));
}
}

public static String getUserId(Metadata requestHeaders) {
String unitInfo = requestHeaders.get(HEAD_KEY_UNIT_INFO);
Map<String, String> unitInfoMap = JSON.parseObject(unitInfo,
new TypeReference<Map<String, String>>() {
});
if (unitInfoMap != null) {
return unitInfoMap.get(USERID_KEY);
}
return null;
}
Comment on lines +307 to +316
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add null check and error handling.

The method should handle null input and JSON parsing errors gracefully.

     public static String getUserId(Metadata requestHeaders) {
+        if (requestHeaders == null) {
+            return null;
+        }
         String unitInfo = requestHeaders.get(HEAD_KEY_UNIT_INFO);
+        if (unitInfo == null) {
+            return null;
+        }
+        try {
             Map<String, String> unitInfoMap = JSON.parseObject(unitInfo,
                 new TypeReference<Map<String, String>>() {
                 });
             if (unitInfoMap != null) {
                 return unitInfoMap.get(USERID_KEY);
             }
             return null;
+        } catch (Exception e) {
+            LOGGER.warn("Failed to parse unit info: " + unitInfo, e);
+            return null;
+        }
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public static String getUserId(Metadata requestHeaders) {
String unitInfo = requestHeaders.get(HEAD_KEY_UNIT_INFO);
Map<String, String> unitInfoMap = JSON.parseObject(unitInfo,
new TypeReference<Map<String, String>>() {
});
if (unitInfoMap != null) {
return unitInfoMap.get(USERID_KEY);
}
return null;
}
public static String getUserId(Metadata requestHeaders) {
if (requestHeaders == null) {
return null;
}
String unitInfo = requestHeaders.get(HEAD_KEY_UNIT_INFO);
if (unitInfo == null) {
return null;
}
try {
Map<String, String> unitInfoMap = JSON.parseObject(unitInfo,
new TypeReference<Map<String, String>>() {
});
if (unitInfoMap != null) {
return unitInfoMap.get(USERID_KEY);
}
return null;
} catch (Exception e) {
LOGGER.warn("Failed to parse unit info: " + unitInfo, e);
return null;
}
}

}
Loading