| 1 |
<?php |
| 2 |
namespace Wikimedia\Telemetry; |
| 3 |
|
| 4 |
use Wikimedia\Assert\Assert; |
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
class Span implements SpanInterface { |
| 13 |
|
| 14 |
private Clock $clock; |
| 15 |
|
| 16 |
private TracerState $tracerState; |
| 17 |
|
| 18 |
private SpanContext $context; |
| 19 |
|
| 20 |
public function __construct( |
| 21 |
Clock $clock, |
| 22 |
TracerState $tracerState, |
| 23 |
SpanContext $context |
| 24 |
) { |
| 25 |
$this->clock = $clock; |
| 26 |
$this->tracerState = $tracerState; |
| 27 |
$this->context = $context; |
| 28 |
} |
| 29 |
|
| 30 |
public function __destruct() { |
| 31 |
$this->end(); |
| 32 |
$activeSpanContext = $this->tracerState->getActiveSpanContext(); |
| 33 |
if ( $this->context->equals( $activeSpanContext ) ) { |
| 34 |
$this->deactivate(); |
| 35 |
} |
| 36 |
} |
| 37 |
|
| 38 |
|
| 39 |
public function getContext(): SpanContext { |
| 40 |
return $this->context; |
| 41 |
} |
| 42 |
|
| 43 |
|
| 44 |
public function setAttributes( array $attributes ): SpanInterface { |
| 45 |
$this->context->setAttributes( $attributes ); |
| 46 |
return $this; |
| 47 |
} |
| 48 |
|
| 49 |
|
| 50 |
public function setSpanKind( int $spanKind ): SpanInterface { |
| 51 |
$this->context->setSpanKind( $spanKind ); |
| 52 |
return $this; |
| 53 |
} |
| 54 |
|
| 55 |
|
| 56 |
public function start( ?int $epochNanos = null ): SpanInterface { |
| 57 |
Assert::precondition( |
| 58 |
!$this->context->wasStarted(), |
| 59 |
'Cannot start a span more than once' |
| 60 |
); |
| 61 |
|
| 62 |
$this->context->setStartEpochNanos( $epochNanos ?? $this->clock->getCurrentNanoTime() ); |
| 63 |
|
| 64 |
return $this; |
| 65 |
} |
| 66 |
|
| 67 |
|
| 68 |
public function end( ?int $epochNanos = null ): void { |
| 69 |
Assert::precondition( |
| 70 |
$this->context->wasStarted(), |
| 71 |
'Cannot end a span that has not been started' |
| 72 |
); |
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
if ( !$this->context->wasEnded() ) { |
| 77 |
$this->context->setEndEpochNanos( $epochNanos ?? $this->clock->getCurrentNanoTime() ); |
| 78 |
$this->tracerState->addSpanContext( $this->context ); |
| 79 |
} |
| 80 |
} |
| 81 |
|
| 82 |
|
| 83 |
public function activate(): void { |
| 84 |
$this->tracerState->activateSpan( $this->getContext() ); |
| 85 |
} |
| 86 |
|
| 87 |
|
| 88 |
public function deactivate(): void { |
| 89 |
$this->tracerState->deactivateSpan( $this->getContext() ); |
| 90 |
} |
| 91 |
|
| 92 |
} |