Skip to content

Commit b5a5ac7

Browse files
authored
Allow immediate gc of ContextStorageNodes after ::detach() (open-telemetry#1585)
Use dummy object instead of self references as detached-marker to avoid relying on gc cycle collection. Resolves open-telemetry#1584.
1 parent 4851a4e commit b5a5ac7

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

src/Context/ContextStorageNode.php

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -52,15 +52,18 @@ public function detach(): int
5252
$flags |= ScopeInterface::INACTIVE;
5353
}
5454

55+
static $detached;
56+
$detached ??= (new \ReflectionClass(self::class))->newInstanceWithoutConstructor();
57+
5558
if ($this === $this->head->node) {
56-
assert($this->previous !== $this);
59+
assert($this->previous !== $detached);
5760
$this->head->node = $this->previous;
58-
$this->previous = $this;
61+
$this->previous = $detached;
5962

6063
return $flags;
6164
}
6265

63-
if ($this->previous === $this) {
66+
if ($this->previous === $detached) {
6467
return $flags | ScopeInterface::DETACHED;
6568
}
6669

@@ -71,7 +74,7 @@ public function detach(): int
7174
assert($n->previous !== null);
7275
}
7376
$n->previous = $this->previous;
74-
$this->previous = $this;
77+
$this->previous = $detached;
7578

7679
return $flags | ScopeInterface::MISMATCH | $depth;
7780
}

tests/Unit/Context/ScopeTest.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,4 +127,16 @@ public function test_scope_local_storage_is_preserved_between_attach_and_scope()
127127
$this->assertNotNull($scope);
128128
$this->assertArrayNotHasKey('key', $scope);
129129
}
130+
131+
public function test_scope_is_gced_after_detach(): void
132+
{
133+
$storage = new ContextStorage();
134+
$scope = $storage->attach($storage->current());
135+
136+
$ref = \WeakReference::create($scope);
137+
$scope->detach();
138+
unset($scope);
139+
140+
$this->assertNull($ref->get());
141+
}
130142
}

0 commit comments

Comments
 (0)