diff --git a/lib/new_relic/distributed_trace/backoff_sampler.ex b/lib/new_relic/distributed_trace/backoff_sampler.ex index c60f40a..b7a946f 100644 --- a/lib/new_relic/distributed_trace/backoff_sampler.ex +++ b/lib/new_relic/distributed_trace/backoff_sampler.ex @@ -26,6 +26,7 @@ defmodule NewRelic.DistributedTrace.BackoffSampler do :persistent_term.put({__MODULE__, :counter}, new(@size, [])) put(@sampling_target, AgentRun.lookup(:sampling_target) || 10) + trigger_next_cycle() {:ok, %{}} end @@ -94,7 +95,7 @@ defmodule NewRelic.DistributedTrace.BackoffSampler do def trigger_next_cycle() do cycle_period = AgentRun.lookup(:sampling_target_period) || 60_000 - Process.send_after(self(), :cycle, cycle_period) + Process.send_after(__MODULE__, :cycle, cycle_period) end def update_state(false = _sampled?) do diff --git a/test/backoff_sampler_test.exs b/test/backoff_sampler_test.exs index 27c9bc2..952923a 100644 --- a/test/backoff_sampler_test.exs +++ b/test/backoff_sampler_test.exs @@ -19,7 +19,7 @@ defmodule BackoffSamplerTest do assert BackoffSampler.sample?() assert BackoffSampler.sample?() - # The rest will be ignored + # The rest will be dropped refute BackoffSampler.sample?() refute BackoffSampler.sample?() refute BackoffSampler.sample?() @@ -96,4 +96,48 @@ defmodule BackoffSamplerTest do decided_count_last: 0 }) end + + test "cycles trigger" do + Application.put_env(:new_relic_agent, :sampling_target_period, 100) + + BackoffSampler.reset() + BackoffSampler.trigger_next_cycle() + + # Target is 10, so it will sample the first 10 + assert BackoffSampler.sample?() + assert BackoffSampler.sample?() + assert BackoffSampler.sample?() + assert BackoffSampler.sample?() + assert BackoffSampler.sample?() + assert BackoffSampler.sample?() + assert BackoffSampler.sample?() + assert BackoffSampler.sample?() + assert BackoffSampler.sample?() + assert BackoffSampler.sample?() + + # The rest will be dropped + refute BackoffSampler.sample?() + refute BackoffSampler.sample?() + refute BackoffSampler.sample?() + refute BackoffSampler.sample?() + + # Wait until the next cycle + Process.sleep(110) + + # Next cycle it will adjust and take some, but not all + decisions = [ + BackoffSampler.sample?(), + BackoffSampler.sample?(), + BackoffSampler.sample?(), + BackoffSampler.sample?(), + BackoffSampler.sample?(), + BackoffSampler.sample?(), + BackoffSampler.sample?(), + BackoffSampler.sample?(), + BackoffSampler.sample?() + ] + + assert true in decisions + assert false in decisions + end end