Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cache tracing #914

Merged
merged 4 commits into from
Jul 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions config/sentry.php
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,9 @@
// Capture HTTP client requests as spans
'http_client_requests' => env('SENTRY_TRACE_HTTP_CLIENT_REQUESTS_ENABLED', true),

// Capture Laravel cache events (hits, writes etc.) as spans
'cache' => env('SENTRY_TRACE_CACHE_ENABLED', true),

// Capture Redis operations as spans (this enables Redis events in Laravel)
'redis_commands' => env('SENTRY_TRACE_REDIS_COMMANDS', false),

Expand Down
132 changes: 126 additions & 6 deletions src/Sentry/Laravel/Features/CacheIntegration.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,22 @@
use Illuminate\Support\Str;
use Sentry\Breadcrumb;
use Sentry\Laravel\Features\Concerns\ResolvesEventOrigin;
use Sentry\Laravel\Features\Concerns\TracksPushedScopesAndSpans;
use Sentry\Laravel\Features\Concerns\WorksWithSpans;
use Sentry\Laravel\Integration;
use Sentry\SentrySdk;
use Sentry\Tracing\Span;
use Sentry\Tracing\SpanContext;
use Sentry\Tracing\SpanStatus;

class CacheIntegration extends Feature
{
use ResolvesEventOrigin;
use WorksWithSpans, TracksPushedScopesAndSpans, ResolvesEventOrigin;

public function isApplicable(): bool
{
return $this->isTracingFeatureEnabled('redis_commands')
return $this->isTracingFeatureEnabled('redis_commands', false)
|| $this->isTracingFeatureEnabled('cache')
|| $this->isBreadcrumbFeatureEnabled('cache');
}

Expand All @@ -31,19 +36,37 @@ public function onBoot(Dispatcher $events): void
Events\CacheMissed::class,
Events\KeyWritten::class,
Events\KeyForgotten::class,
], [$this, 'handleCacheEvent']);
], [$this, 'handleCacheEventsForBreadcrumbs']);
}

if ($this->isTracingFeatureEnabled('cache')) {
$events->listen([
Events\RetrievingKey::class,
Events\RetrievingManyKeys::class,
Events\CacheHit::class,
Events\CacheMissed::class,

Events\WritingKey::class,
Events\WritingManyKeys::class,
Events\KeyWritten::class,
Events\KeyWriteFailed::class,

Events\ForgettingKey::class,
Events\KeyForgotten::class,
Events\KeyForgetFailed::class,
], [$this, 'handleCacheEventsForTracing']);
}

if ($this->isTracingFeatureEnabled('redis_commands', false)) {
$events->listen(RedisEvents\CommandExecuted::class, [$this, 'handleRedisCommand']);
$events->listen(RedisEvents\CommandExecuted::class, [$this, 'handleRedisCommands']);

$this->container()->afterResolving(RedisManager::class, static function (RedisManager $redis): void {
$redis->enableEvents();
});
}
}

public function handleCacheEvent(Events\CacheEvent $event): void
public function handleCacheEventsForBreadcrumbs(Events\CacheEvent $event): void
{
switch (true) {
case $event instanceof Events\KeyWritten:
Expand Down Expand Up @@ -72,7 +95,64 @@ public function handleCacheEvent(Events\CacheEvent $event): void
));
}

public function handleRedisCommand(RedisEvents\CommandExecuted $event): void
public function handleCacheEventsForTracing(Events\CacheEvent $event): void
{
if ($this->maybeHandleCacheEventAsEndOfSpan($event)) {
return;
}

$this->withParentSpanIfSampled(function (Span $parentSpan) use ($event) {
if ($event instanceof Events\RetrievingKey || $event instanceof Events\RetrievingManyKeys) {
$keys = $event instanceof Events\RetrievingKey
? [$event->key]
: $event->keys;

$this->pushSpan(
$parentSpan->startChild(
SpanContext::make()
->setOp('cache.get')
->setData([
'cache.key' => $keys,
])
->setDescription(implode(', ', $keys))
)
);
}

if ($event instanceof Events\WritingKey || $event instanceof Events\WritingManyKeys) {
$keys = $event instanceof Events\WritingKey
? [$event->key]
: $event->keys;

$this->pushSpan(
$parentSpan->startChild(
SpanContext::make()
->setOp('cache.put')
->setData([
'cache.key' => $keys,
'cache.ttl' => $event->seconds,
])
->setDescription(implode(', ', $keys))
)
);
}

if ($event instanceof Events\ForgettingKey) {
$this->pushSpan(
$parentSpan->startChild(
SpanContext::make()
->setOp('cache.remove')
->setData([
'cache.key' => [$event->key],
])
->setDescription($event->key)
)
);
}
});
}

public function handleRedisCommands(RedisEvents\CommandExecuted $event): void
{
$parentSpan = SentrySdk::getCurrentHub()->getSpan();

Expand Down Expand Up @@ -116,4 +196,44 @@ public function handleRedisCommand(RedisEvents\CommandExecuted $event): void

$parentSpan->startChild($context);
}

private function maybeHandleCacheEventAsEndOfSpan(Events\CacheEvent $event): bool
{
// End of span for RetrievingKey and RetrievingManyKeys events
if ($event instanceof Events\CacheHit || $event instanceof Events\CacheMissed) {
$finishedSpan = $this->maybeFinishSpan(SpanStatus::ok());

if ($finishedSpan !== null && count($finishedSpan->getData()['cache.key'] ?? []) === 1) {
$finishedSpan->setData([
'cache.hit' => $event instanceof Events\CacheHit,
]);
}

return true;
}

// End of span for WritingKey and WritingManyKeys events
if ($event instanceof Events\KeyWritten || $event instanceof Events\KeyWriteFailed) {
$finishedSpan = $this->maybeFinishSpan(
$event instanceof Events\KeyWritten ? SpanStatus::ok() : SpanStatus::internalError()
);

if ($finishedSpan !== null) {
$finishedSpan->setData([
'cache.success' => $event instanceof Events\KeyWritten,
]);
}

return true;
}

// End of span for ForgettingKey event
if ($event instanceof Events\KeyForgotten || $event instanceof Events\KeyForgetFailed) {
$this->maybeFinishSpan();

return true;
}

return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Sentry\Laravel\Integration;
use Sentry\SentrySdk;
use Sentry\Tracing\Span;
use Sentry\Tracing\SpanStatus;

trait TracksPushedScopesAndSpans
{
Expand Down Expand Up @@ -72,4 +73,21 @@ protected function maybePopScope(): void

--$this->pushedScopeCount;
}

protected function maybeFinishSpan(?SpanStatus $status = null): ?Span
{
$span = $this->maybePopSpan();

if ($span === null) {
return null;
}

if ($status !== null) {
$span->setStatus($status);
}

$span->finish();

return $span;
}
}
33 changes: 33 additions & 0 deletions src/Sentry/Laravel/Features/Concerns/WorksWithSpans.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

namespace Sentry\Laravel\Features\Concerns;

use Sentry\SentrySdk;
use Sentry\Tracing\Span;

trait WorksWithSpans
{
protected function getParentSpanIfSampled(): ?Span
{
$parentSpan = SentrySdk::getCurrentHub()->getSpan();

// If the span is not available or not sampled we don't need to do anything
if ($parentSpan === null || !$parentSpan->getSampled()) {
return null;
}

return $parentSpan;
}

/** @param callable(Span $parentSpan): void $callback */
protected function withParentSpanIfSampled(callable $callback): void
{
$parentSpan = $this->getParentSpanIfSampled();

if ($parentSpan === null) {
return;
}

$callback($parentSpan);
}
}
7 changes: 1 addition & 6 deletions src/Sentry/Laravel/Features/HttpClientIntegration.php
Original file line number Diff line number Diff line change
Expand Up @@ -108,12 +108,7 @@ public function handleResponseReceivedHandlerForTracing(ResponseReceived $event)

public function handleConnectionFailedHandlerForTracing(ConnectionFailed $event): void
{
$span = $this->maybePopSpan();

if ($span !== null) {
$span->setStatus(SpanStatus::internalError());
$span->finish();
}
$this->maybeFinishSpan(SpanStatus::internalError());
}

public function handleResponseReceivedHandlerForBreadcrumb(ResponseReceived $event): void
Expand Down
6 changes: 1 addition & 5 deletions src/Sentry/Laravel/Features/LivewirePackageIntegration.php
Original file line number Diff line number Diff line change
Expand Up @@ -168,11 +168,7 @@ public function handleComponentHydrate(Component $component): void

public function handleComponentDehydrate(Component $component): void
{
$span = $this->maybePopSpan();

if ($span !== null) {
$span->finish();
}
$span = $this->maybeFinishSpan();
}

private function updateTransactionName(string $componentName): void
Expand Down
12 changes: 1 addition & 11 deletions src/Sentry/Laravel/Features/NotificationsIntegration.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public function handleNotificationSending(NotificationSending $event): void

public function handleNotificationSent(NotificationSent $event): void
{
$this->finishSpanWithStatus(SpanStatus::ok());
$this->maybeFinishSpan(SpanStatus::ok());

if ($this->isBreadcrumbFeatureEnabled(self::FEATURE_KEY)) {
Integration::addBreadcrumb(new Breadcrumb(
Expand All @@ -75,16 +75,6 @@ public function handleNotificationSent(NotificationSent $event): void
}
}

private function finishSpanWithStatus(SpanStatus $status): void
{
$span = $this->maybePopSpan();

if ($span !== null) {
$span->setStatus($status);
$span->finish();
}
}

private function formatNotifiable(object $notifiable): string
{
$notifiable = get_class($notifiable);
Expand Down
20 changes: 3 additions & 17 deletions src/Sentry/Laravel/Features/QueueIntegration.php
Original file line number Diff line number Diff line change
Expand Up @@ -112,16 +112,12 @@ public function handleJobQueueingEvent(JobQueueing $event): void

public function handleJobQueuedEvent(JobQueued $event): void
{
$span = $this->maybePopSpan();

if ($span !== null) {
$span->finish();
}
$this->maybeFinishSpan();
}

public function handleJobProcessedQueueEvent(JobProcessed $event): void
{
$this->finishJobWithStatus(SpanStatus::ok());
$this->maybeFinishSpan(SpanStatus::ok());

$this->maybePopScope();
}
Expand Down Expand Up @@ -225,21 +221,11 @@ public function handleWorkerStoppingQueueEvent(WorkerStopping $event): void

public function handleJobExceptionOccurredQueueEvent(JobExceptionOccurred $event): void
{
$this->finishJobWithStatus(SpanStatus::internalError());
$this->maybeFinishSpan(SpanStatus::internalError());

Integration::flushEvents();
}

private function finishJobWithStatus(SpanStatus $status): void
{
$span = $this->maybePopSpan();

if ($span !== null) {
$span->setStatus($status);
$span->finish();
}
}

private function normalizeQueueName(?string $queue): string
{
if ($queue === null) {
Expand Down
Loading