package com.sckw.remote.filter;

import com.sckw.remote.utils.UuidUtils;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.slf4j.MDC;

/**
 * @desc: dubbo调用全局链路id
 * @author: yzc
 * @date: 2023-08-23 10:09
 */
@Activate(group = {CommonConstants.PROVIDER, CommonConstants.CONSUMER})
public class TraceIdFilter implements Filter {
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        RpcServiceContext rpcContext = RpcContext.getServiceContext();
        String traceId;
        if (rpcContext.isConsumerSide()) {
            traceId = MDC.get("traceId");
            if (traceId == null) {
                traceId = UuidUtils.getUuid();
            }
            rpcContext.setAttachment("traceId", traceId);
        }
        if (rpcContext.isProviderSide()) {
            traceId = rpcContext.getAttachment("traceId");
            MDC.put("traceId", traceId);
        }
        return invoker.invoke(invocation);
    }
}
