TraceRpcClient.php 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <?php
  2. namespace think\swoole\middleware;
  3. use think\swoole\exception\RpcResponseException;
  4. use think\swoole\rpc\Protocol;
  5. use think\tracing\Tracer;
  6. use Throwable;
  7. use const OpenTracing\Formats\TEXT_MAP;
  8. use const OpenTracing\Tags\ERROR;
  9. use const OpenTracing\Tags\SPAN_KIND;
  10. use const OpenTracing\Tags\SPAN_KIND_RPC_CLIENT;
  11. class TraceRpcClient
  12. {
  13. protected $tracer;
  14. public function __construct(Tracer $tracer)
  15. {
  16. $this->tracer = $tracer;
  17. }
  18. public function handle(Protocol $protocol, $next)
  19. {
  20. $scope = $this->tracer->startActiveSpan(
  21. 'rpc.client:' . $protocol->getInterface() . '@' . $protocol->getMethod(),
  22. [
  23. 'tags' => [
  24. SPAN_KIND => SPAN_KIND_RPC_CLIENT,
  25. ],
  26. ]
  27. );
  28. $span = $scope->getSpan();
  29. $context = $protocol->getContext();
  30. $this->tracer->inject($span->getContext(), TEXT_MAP, $context);
  31. $protocol->setContext($context);
  32. try {
  33. return $next($protocol);
  34. } catch (Throwable $e) {
  35. if (!$e instanceof RpcResponseException) {
  36. $span->setTag(ERROR, $e);
  37. }
  38. throw $e;
  39. } finally {
  40. $scope->close();
  41. }
  42. }
  43. }