Skip to content
Open
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
29 changes: 29 additions & 0 deletions src/Options.php
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,33 @@ public function setProfilesSampler(?callable $sampler): self
return $this->updateOptions(['profiles_sampler' => $sampler]);
}

/**
* Gets the factory used to create a profiler for each sampled transaction.
*
* @phpstan-return null|callable(Options): Profiling\ProfilerInterface
*/
public function getProfilerFactory(): ?callable
{
/** @var callable(Options): Profiling\ProfilerInterface|null $value */
$value = $this->options['profiler_factory'];

return $value;
}

/**
* Sets the factory used to create a profiler for each sampled transaction.
* Return a new profiler for each transaction so concurrent profiles remain independent.
* When null, the SDK uses its default Excimer profiler.
*
* @param ?callable $factory The factory
*
* @phpstan-param null|callable(Options): Profiling\ProfilerInterface $factory
*/
public function setProfilerFactory(?callable $factory): self
{
return $this->updateOptions(['profiler_factory' => $factory]);
}

/**
* Gets whether tracing is enabled or not. The feature is enabled when at
* least one of the `traces_sample_rate` and `traces_sampler` options is
Expand Down Expand Up @@ -1262,6 +1289,7 @@ private function configureOptions(OptionsResolver $resolver): void
$resolver->setAllowedTypes('traces_sampler', ['null', 'callable']);
$resolver->setAllowedTypes('profiles_sample_rate', ['null', 'int', 'float']);
$resolver->setAllowedTypes('profiles_sampler', ['null', 'callable']);
$resolver->setAllowedTypes('profiler_factory', ['null', 'callable']);
$resolver->setAllowedTypes('attach_stacktrace', 'bool');
$resolver->setAllowedTypes('attach_metric_code_locations', 'bool');
$resolver->setAllowedTypes('context_lines', ['null', 'int']);
Expand Down Expand Up @@ -1347,6 +1375,7 @@ private function configureOptions(OptionsResolver $resolver): void
'traces_sampler' => null,
'profiles_sample_rate' => null,
'profiles_sampler' => null,
'profiler_factory' => null,
'attach_stacktrace' => false,
/**
* @deprecated Metrics are no longer supported. Metrics API is a no-op and will be removed in 5.x.
Expand Down
9 changes: 7 additions & 2 deletions src/Profiling/Profile.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,6 @@
* trace: array<int, ExcimerLogStackEntryTrace>,
* timestamp: float
* }
*
* @internal
*/
final class Profile
{
Expand Down Expand Up @@ -137,20 +135,27 @@ public function setStartTimeStamp(float $startTimeStamp): void
}

/**
* Entry timestamps are offsets in seconds from the profile's start timestamp.
*
* @param \ExcimerLog|array<int, ExcimerLogStackEntry> $excimerLog
*/
public function setExcimerLog($excimerLog): void
{
$this->excimerLog = $excimerLog;
}

/**
* @internal
*/
public function setEventId(EventId $eventId): void
{
$this->eventId = $eventId;
}

/**
* @return SentryProfile|null
*
* @internal
*/
public function getFormattedData(Event $event): ?array
{
Expand Down
2 changes: 1 addition & 1 deletion src/Profiling/Profiler.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
/**
* @internal
*/
final class Profiler
final class Profiler implements ProfilerInterface
{
/**
* @var \ExcimerProfiler|null
Expand Down
14 changes: 14 additions & 0 deletions src/Profiling/ProfilerInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

declare(strict_types=1);

namespace Sentry\Profiling;

interface ProfilerInterface
{
public function start(): void;

public function stop(): void;

public function getProfile(): ?Profile;
}
7 changes: 6 additions & 1 deletion src/State/Hub.php
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,12 @@ public function startTransaction(TransactionContext $context, array $customSampl
} elseif ($this->sample($profilesSampleRate)) {
$logger->info(\sprintf('Transaction [%s] started profiling because it was sampled.', (string) $transaction->getTraceId()));

$transaction->initProfiler()->start();
try {
$transaction->initProfiler()->start();
} catch (\Throwable $exception) {
$transaction->detachProfiler();
$logger->error(\sprintf('Failed to start the profiler. Reason: "%s".', $exception->getMessage()), ['exception' => $exception]);
}
} else {
$logger->info(\sprintf('Transaction [%s] is not profiling because it was not sampled.', (string) $transaction->getTraceId()));
}
Expand Down
43 changes: 30 additions & 13 deletions src/Tracing/Transaction.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@

use Sentry\Event;
use Sentry\EventId;
use Sentry\Profiling\Profile;
use Sentry\Profiling\Profiler;
use Sentry\Profiling\ProfilerInterface;
use Sentry\SentrySdk;
use Sentry\State\HubInterface;

Expand Down Expand Up @@ -36,7 +38,7 @@ final class Transaction extends Span
protected $metadata;

/**
* @var Profiler|null Reference instance to the {@see Profiler}
* @var ProfilerInterface|null
*/
protected $profiler;

Expand Down Expand Up @@ -119,19 +121,23 @@ public function initSpanRecorder(int $maxSpans = 1000): self
return $this;
}

public function initProfiler(): Profiler
public function initProfiler(): ProfilerInterface
{
if ($this->profiler === null) {
$client = $this->hub->getClient();
$options = $client !== null ? $client->getOptions() : null;

$this->profiler = new Profiler($options);
if ($options !== null && ($factory = $options->getProfilerFactory()) !== null) {
$this->profiler = $factory($options);
} else {
$this->profiler = new Profiler($options);
}
}

return $this->profiler;
}

public function getProfiler(): ?Profiler
public function getProfiler(): ?ProfilerInterface
{
return $this->profiler;
}
Expand All @@ -148,15 +154,13 @@ public function detachProfiler(): self
*/
public function finish(?float $endTimestamp = null): ?EventId
{
if ($this->profiler !== null) {
$this->profiler->stop();
}

if ($this->endTimestamp !== null) {
// Transaction was already finished once and we don't want to re-flush it
return null;
}

$profile = $this->profiler !== null ? $this->finishProfiler($this->profiler) : null;

parent::finish($endTimestamp);

if ($this->sampled !== true) {
Expand All @@ -183,13 +187,26 @@ public function finish(?float $endTimestamp = null): ?EventId
$event->setSdkMetadata('dynamic_sampling_context', $this->getDynamicSamplingContext());
$event->setSdkMetadata('transaction_metadata', $this->getMetadata());

if ($this->profiler !== null) {
$profile = $this->profiler->getProfile();
if ($profile !== null) {
$event->setSdkMetadata('profile', $profile);
}
if ($profile !== null) {
$event->setSdkMetadata('profile', $profile);
}

return $this->hub->captureEvent($event);
}

private function finishProfiler(ProfilerInterface $profiler): ?Profile
{
try {
$profiler->stop();

return $this->sampled === true ? $profiler->getProfile() : null;
} catch (\Throwable $exception) {
$client = $this->hub->getClient();
if ($client !== null) {
$client->getOptions()->getLoggerOrNullLogger()->error(\sprintf('Failed to stop the profiler. Reason: "%s".', $exception->getMessage()), ['exception' => $exception]);
}

return null;
}
}
}
1 change: 1 addition & 0 deletions src/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@
* max_value_length?: int,
* org_id?: int|null,
* prefixes?: array<string>,
* profiler_factory?: callable|null,
* profiles_sample_rate?: int|float|null,
* profiles_sampler?: callable|null,
* release?: string|null,
Expand Down
8 changes: 8 additions & 0 deletions tests/OptionsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,13 @@ static function (): void {},
'setProfilesSampler',
];

yield [
'profiler_factory',
static function (): void {},
'getProfilerFactory',
'setProfilerFactory',
];

yield [
'attach_stacktrace',
false,
Expand Down Expand Up @@ -606,6 +613,7 @@ public function testDefaultOptionValues(): void
'traces_sampler' => null,
'profiles_sample_rate' => null,
'profiles_sampler' => null,
'profiler_factory' => null,
'attach_stacktrace' => false,
'attach_metric_code_locations' => false,
'context_lines' => 5,
Expand Down
56 changes: 56 additions & 0 deletions tests/State/HubTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use Sentry\MonitorConfig;
use Sentry\MonitorSchedule;
use Sentry\Options;
use Sentry\Profiling\ProfilerInterface;
use Sentry\Severity;
use Sentry\State\Hub;
use Sentry\State\Scope;
Expand Down Expand Up @@ -917,6 +918,61 @@ public function testStartTransactionStartsProfilerWithProfilesSampler(): void
$this->assertNotNull($transaction->getProfiler());
}

public function testStartTransactionCreatesAProfilerForEachSampledTransaction(): void
{
$profilers = [
$this->createMock(ProfilerInterface::class),
$this->createMock(ProfilerInterface::class),
];
foreach ($profilers as $profiler) {
$profiler->expects($this->once())->method('start');
}
$calls = 0;
$options = new Options([
'traces_sample_rate' => 1.0,
'profiles_sample_rate' => 1.0,
]);
$options->setProfilerFactory(function (Options $factoryOptions) use ($options, $profilers, &$calls): ProfilerInterface {
$this->assertSame($options, $factoryOptions);

return $profilers[$calls++];
});
$client = $this->createMock(ClientInterface::class);
$client->method('getOptions')->willReturn($options);
$hub = new Hub($client);

foreach ($profilers as $profiler) {
$transaction = $hub->startTransaction(new TransactionContext());

$this->assertSame($profiler, $transaction->getProfiler());
}
}

public function testProfilerFactoryExceptionDropsProfileAndIsLogged(): void
{
StubLogger::$logs = [];
$exception = new \RuntimeException('test');
$client = $this->createMock(ClientInterface::class);
$client->method('getOptions')->willReturn(new Options([
'logger' => StubLogger::getInstance(),
'traces_sample_rate' => 1.0,
'profiles_sample_rate' => 1.0,
'profiler_factory' => static function () use ($exception): void {
throw $exception;
},
]));

$transaction = (new Hub($client))->startTransaction(new TransactionContext());

$this->assertTrue($transaction->getSampled());
$this->assertNull($transaction->getProfiler());
$this->assertContains([
'level' => 'error',
'message' => 'Failed to start the profiler. Reason: "test".',
'context' => ['exception' => $exception],
], StubLogger::$logs);
}

public function testStartTransactionDoesNotStartProfilerWhenProfilesSamplerReturnsZero(): void
{
$client = $this->createMock(ClientInterface::class);
Expand Down
63 changes: 63 additions & 0 deletions tests/Tracing/TransactionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,11 @@
use Sentry\EventId;
use Sentry\EventType;
use Sentry\Options;
use Sentry\Profiling\Profile;
use Sentry\Profiling\ProfilerInterface;
use Sentry\State\Hub;
use Sentry\State\HubInterface;
use Sentry\Tests\StubLogger;
use Sentry\Tests\TestUtil\ClockMock;
use Sentry\Tracing\SpanContext;
use Sentry\Tracing\Transaction;
Expand Down Expand Up @@ -85,6 +88,66 @@ public function testFinishDoesNothingIfSampledFlagIsNotTrue(): void
$transaction->finish();
}

public function testFinishIncludesTheCustomProfile(): void
{
$profile = new Profile();
$profiler = $this->createMock(ProfilerInterface::class);
$profiler->expects($this->once())->method('stop');
$profiler->expects($this->once())->method('getProfile')->willReturn($profile);
$options = new Options([
'profiler_factory' => static function () use ($profiler): ProfilerInterface {
return $profiler;
},
]);
$client = $this->createMock(ClientInterface::class);
$client->method('getOptions')->willReturn($options);
$hub = $this->createMock(HubInterface::class);
$hub->method('getClient')->willReturn($client);
$hub->expects($this->once())
->method('captureEvent')
->with($this->callback(static function (Event $event) use ($profile): bool {
return $event->getSdkMetadata('profile') === $profile;
}));

$transaction = new Transaction(TransactionContext::make()->setSampled(true), $hub);
$transaction->initProfiler();
$transaction->finish();
$transaction->finish();
}

public function testProfilerExceptionDoesNotPreventFinishingTheTransaction(): void
{
StubLogger::$logs = [];
$exception = new \RuntimeException('test');
$profiler = $this->createMock(ProfilerInterface::class);
$profiler->expects($this->once())->method('stop')->willThrowException($exception);
$profiler->expects($this->never())->method('getProfile');
$client = $this->createMock(ClientInterface::class);
$client->method('getOptions')->willReturn(new Options([
'logger' => StubLogger::getInstance(),
'profiler_factory' => static function () use ($profiler): ProfilerInterface {
return $profiler;
},
]));
$hub = $this->createMock(HubInterface::class);
$hub->method('getClient')->willReturn($client);
$hub->expects($this->once())
->method('captureEvent')
->with($this->callback(static function (Event $event): bool {
return $event->getSdkMetadata('profile') === null;
}));

$transaction = new Transaction(TransactionContext::make()->setSampled(true), $hub);
$transaction->initProfiler();
$transaction->finish();

$this->assertContains([
'level' => 'error',
'message' => 'Failed to stop the profiler. Reason: "test".',
'context' => ['exception' => $exception],
], StubLogger::$logs);
}

public function testFluentApi(): void
{
$transaction = new Transaction(TransactionContext::make());
Expand Down
Loading