From 164ce605a0ca67088c75078b636d02f80d9ec41a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gabriel=20Ostroluck=C3=BD?= Date: Thu, 30 May 2024 12:32:09 +0200 Subject: [PATCH] Fix linking with newrelic.distributed_tracing_enabled=1 There are several behavioural differences with `newrelic.distributed_tracing_enabled=1` that this patch addresses 1. `newrelic_add_custom_parameter('traceId', $value);` hack does not work. Traces do not get traceId matching $value assigned 2. As an obvious solution, custom TraceIdFactory which uses `newrelic_get_trace_metadata` instead of UUIDs presents itself. However, this also does not work, because: 3. Transaction ID apparently might change at any point of time during the request. Specifically, I've observed `newrelic_name_transaction` changes this ID. This bundle in sequence: 1. creates TraceID at beginning of request 2. calls `newrelic_name_transaction` 3. calls `newrelic_add_custom_parameter('traceId', $this->traceId->__toString());` This doesn't work, because step 3 uses ID generated at step 1, but NR changed ID in step 2, hence Logs get different `trace.id` assigned than NR Transaction has. This _could_ be solved by custom NewrelicNativeTraceIdFactory + calling `$this->traceId->refresh()` right after `$this->interactor->setApplicationName(` but I worry that this might work in this case, but there will be other cases where NR extension changes current traceId. Hence, I think solution in this commit is quite robust and will work with both states of `newrelic.distributed_tracing_enabled` out of the box. Only disadvantage is that if users have `newrelic.distributed_tracing_enabled=1`, even if they define custom traceIdFactory, "native" NR transaction ID will be used despite whatever they generate in their custom factory. However, I believe this is OK, because whatever they generate in their custom factory wouldn't be taken over by NR extension anyways, because of very first point mentioned in this commit message --- src/Trace/TraceId.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Trace/TraceId.php b/src/Trace/TraceId.php index edfb496..cfb1a6f 100644 --- a/src/Trace/TraceId.php +++ b/src/Trace/TraceId.php @@ -15,17 +15,17 @@ class TraceId implements \Stringable { - public function __construct(private string $value) + public function __construct(private string $fallbackValue) { } public function __toString(): string { - return $this->value; + return newrelic_get_trace_metadata()['trace_id'] ?? $this->fallbackValue; } public function refresh(self $new): void { - $this->value = $new->value; + $this->fallbackValue = $new->fallbackValue; } }