TraceRpcServer.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <?php
  2. namespace think\swoole\middleware;
  3. use Swoole\Coroutine;
  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_SERVER;
  11. class TraceRpcServer
  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. $context = $this->tracer->extract(TEXT_MAP, $protocol->getContext());
  21. $scope = $this->tracer->startActiveSpan(
  22. 'rpc.server:' . $protocol->getInterface() . '@' . $protocol->getMethod(),
  23. [
  24. 'child_of' => $context,
  25. 'tags' => [
  26. SPAN_KIND => SPAN_KIND_RPC_SERVER,
  27. ],
  28. ]
  29. );
  30. $span = $scope->getSpan();
  31. try {
  32. return $next($protocol);
  33. } catch (Throwable $e) {
  34. $span->setTag(ERROR, $e);
  35. throw $e;
  36. } finally {
  37. $scope->close();
  38. Coroutine::defer(function () {
  39. $this->tracer->flush();
  40. });
  41. }
  42. }
  43. }