diff --git a/src/Sentry/Laravel/Tracing/Middleware.php b/src/Sentry/Laravel/Tracing/Middleware.php index eb390263..308d7d33 100644 --- a/src/Sentry/Laravel/Tracing/Middleware.php +++ b/src/Sentry/Laravel/Tracing/Middleware.php @@ -73,7 +73,7 @@ public function __construct(bool $continueAfterResponse = true) public function handle(Request $request, Closure $next) { if (app()->bound(HubInterface::class)) { - $this->startTransaction($request, app(HubInterface::class)); + $this->startTransaction($request); } return $next($request); @@ -89,12 +89,14 @@ public function handle(Request $request, Closure $next) */ public function terminate(Request $request, $response): void { - // If there is no transaction or the HubInterface is not bound in the container there is nothing for us to do - if ($this->transaction === null || !app()->bound(HubInterface::class)) { + // If there is no transaction there is nothing for us to do + if ($this->transaction === null) { return; } if ($this->shouldRouteBeIgnored($request)) { + $this->discardTransaction(); + return; } @@ -132,10 +134,12 @@ public function setBootedTimestamp(?float $timestamp = null): void $this->bootedTimestamp = $timestamp ?? microtime(true); } - private function startTransaction(Request $request, HubInterface $sentry): void + private function startTransaction(Request $request): void { + $hub = SentrySdk::getCurrentHub(); + // Prevent starting a new transaction if we are already in a transaction - if ($sentry->getTransaction() !== null) { + if ($hub->getTransaction() !== null) { return; } @@ -168,9 +172,9 @@ private function startTransaction(Request $request, HubInterface $sentry): void 'http.request.method' => strtoupper($request->method()), ]); - $transaction = $sentry->startTransaction($context); + $transaction = $hub->startTransaction($context); - SentrySdk::getCurrentHub()->setSpan($transaction); + $hub->setSpan($transaction); // If this transaction is not sampled, we can stop here to prevent doing work for nothing if (!$transaction->getSampled()) { @@ -188,7 +192,17 @@ private function startTransaction(Request $request, HubInterface $sentry): void ->setStartTimestamp($bootstrapSpan ? $bootstrapSpan->getEndTimestamp() : microtime(true)) ); - SentrySdk::getCurrentHub()->setSpan($this->appSpan); + $hub->setSpan($this->appSpan); + } + + private function discardTransaction(): void + { + $this->appSpan = null; + $this->transaction = null; + $this->didRouteMatch = false; + $this->bootedTimestamp = null; + + SentrySdk::getCurrentHub()->setSpan(null); } private function addAppBootstrapSpan(): ?Span