-
Notifications
You must be signed in to change notification settings - Fork 0
/
FiberBoundContextStorage.php
79 lines (61 loc) · 2.15 KB
/
FiberBoundContextStorage.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<?php
declare(strict_types=1);
namespace OpenTelemetry\Context;
use function assert;
use const E_USER_WARNING;
use Fiber;
use function spl_object_id;
use function sprintf;
use function trigger_error;
use WeakMap;
/**
* @internal
*/
final class FiberBoundContextStorage implements ContextStorageInterface, ContextStorageHeadAware
{
/** @var WeakMap<object, ContextStorageHead> */
private WeakMap $heads;
public function __construct()
{
$this->heads = new WeakMap();
$this->heads[$this] = new ContextStorageHead($this);
}
public function head(): ?ContextStorageHead
{
return $this->heads[Fiber::getCurrent() ?? $this] ?? null;
}
public function scope(): ?ContextStorageScopeInterface
{
$head = $this->heads[Fiber::getCurrent() ?? $this] ?? null;
if (!$head?->node && Fiber::getCurrent()) {
self::triggerNotInitializedFiberContextWarning();
return null;
}
// Starts with empty head instead of cloned parent -> no need to check for head mismatch
return $head->node;
}
public function current(): ContextInterface
{
$head = $this->heads[Fiber::getCurrent() ?? $this] ?? null;
if (!$head?->node && Fiber::getCurrent()) {
self::triggerNotInitializedFiberContextWarning();
// Fallback to {main} to preserve BC
$head = $this->heads[$this];
}
return $head->node->context ?? Context::getRoot();
}
public function attach(ContextInterface $context): ContextStorageScopeInterface
{
$head = $this->heads[Fiber::getCurrent() ?? $this] ??= new ContextStorageHead($this);
return $head->node = new ContextStorageNode($context, $head, $head->node);
}
private static function triggerNotInitializedFiberContextWarning(): void
{
$fiber = Fiber::getCurrent();
assert($fiber !== null);
trigger_error(sprintf(
'Access to not initialized OpenTelemetry context in fiber (id: %d), automatic forking not supported, must attach initial fiber context manually',
spl_object_id($fiber),
), E_USER_WARNING);
}
}