Skip to content

Commit

Permalink
Merge branch 'radostyle-datadog-rate-limit'
Browse files Browse the repository at this point in the history
  • Loading branch information
magikid committed Nov 29, 2023
2 parents 0bc1b61 + 9fc9ac6 commit 99a8a8a
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/Profiler/DatadogProfiler.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,17 @@ class DatadogProfiler implements ProfilerInterface

private LoggerInterface $logger;

private float $sampleRate = 1.0;

public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;

$sampleRateString = getenv('DD_TRACE_SAMPLE_RATE');
if(is_numeric($sampleRateString)) {
$sampleRate = floatval($sampleRateString);
$this->sampleRate = $sampleRate;
}
}

public function start(string $name, ?string $kind = null): void
Expand All @@ -33,6 +41,10 @@ public function start(string $name, ?string $kind = null): void
return;
}

if($this->rateLimited()) {
return;
}

if (dd_trace_env_config('DD_TRACE_GENERATE_ROOT_SPAN')) {
$this->logger->error(
sprintf('You should set DD_TRACE_GENERATE_ROOT_SPAN=0 when using %s.', self::class)
Expand Down Expand Up @@ -89,6 +101,12 @@ public function stopAndIgnore(): void
GlobalTracer::set(new Tracer());
}

private function rateLimited(): bool
{
$randomFloat = mt_rand() / mt_getrandmax(); // between 0 and 1
return $randomFloat > $this->sampleRate;
}

private function isEnabled(): bool
{
return \extension_loaded('ddtrace')
Expand Down

0 comments on commit 99a8a8a

Please sign in to comment.