-
Notifications
You must be signed in to change notification settings - Fork 30
/
DriverSuspension.php
196 lines (152 loc) · 5.91 KB
/
DriverSuspension.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
<?php
/** @noinspection PhpPropertyOnlyWrittenInspection */
declare(strict_types=1);
namespace Revolt\EventLoop\Internal;
use Revolt\EventLoop\Suspension;
/**
* @internal
*
* @template T
* @implements Suspension<T>
*/
final class DriverSuspension implements Suspension
{
private ?\Fiber $suspendedFiber = null;
/** @var \WeakReference<\Fiber>|null */
private readonly ?\WeakReference $fiberRef;
private ?\Error $error = null;
private bool $pending = false;
private bool $deadMain = false;
/**
* @param \WeakMap<object, \WeakReference<DriverSuspension>> $suspensions
*/
public function __construct(
private readonly \Closure $run,
private readonly \Closure $queue,
private readonly \Closure $interrupt,
private readonly \WeakMap $suspensions,
) {
$fiber = \Fiber::getCurrent();
$this->fiberRef = $fiber ? \WeakReference::create($fiber) : null;
}
public function resume(mixed $value = null): void
{
// Ignore spurious resumes to old dead {main} suspension
if ($this->deadMain) {
return;
}
if (!$this->pending) {
throw $this->error ?? new \Error('Must call suspend() before calling resume()');
}
$this->pending = false;
/** @var \Fiber|null $fiber */
$fiber = $this->fiberRef?->get();
if ($fiber) {
($this->queue)(static function () use ($fiber, $value): void {
// The fiber may be destroyed with suspension as part of the GC cycle collector.
if (!$fiber->isTerminated()) {
$fiber->resume($value);
}
});
} else {
// Suspend event loop fiber to {main}.
($this->interrupt)(static fn () => $value);
}
}
public function suspend(): mixed
{
// Throw exception when trying to use old dead {main} suspension
if ($this->deadMain) {
throw new \Error(
'Suspension cannot be suspended after an uncaught exception is thrown from the event loop',
);
}
if ($this->pending) {
throw new \Error('Must call resume() or throw() before calling suspend() again');
}
$fiber = $this->fiberRef?->get();
if ($fiber !== \Fiber::getCurrent()) {
throw new \Error('Must not call suspend() from another fiber');
}
$this->pending = true;
$this->error = null;
// Awaiting from within a fiber.
if ($fiber) {
$this->suspendedFiber = $fiber;
try {
$value = \Fiber::suspend();
$this->suspendedFiber = null;
} catch (\FiberError $error) {
$this->pending = false;
$this->suspendedFiber = null;
$this->error = $error;
throw $error;
}
// Setting $this->suspendedFiber = null in finally will set the fiber to null if a fiber is destroyed
// as part of a cycle collection, causing an error if the suspension is subsequently resumed.
return $value;
}
// Awaiting from {main}.
$result = ($this->run)();
/** @psalm-suppress RedundantCondition $this->pending should be changed when resumed. */
if ($this->pending) {
// This is now a dead {main} suspension.
$this->deadMain = true;
// Unset suspension for {main} using queue closure.
unset($this->suspensions[$this->queue]);
$result && $result(); // Unwrap any uncaught exceptions from the event loop
\gc_collect_cycles(); // Collect any circular references before dumping pending suspensions.
$info = '';
foreach ($this->suspensions as $suspensionRef) {
if ($suspension = $suspensionRef->get()) {
\assert($suspension instanceof self);
$fiber = $suspension->fiberRef?->get();
if ($fiber === null) {
continue;
}
$reflectionFiber = new \ReflectionFiber($fiber);
$info .= "\n\n" . $this->formatStacktrace($reflectionFiber->getTrace(\DEBUG_BACKTRACE_IGNORE_ARGS));
}
}
throw new \Error('Event loop terminated without resuming the current suspension (the cause is either a fiber deadlock, or an incorrectly unreferenced/canceled watcher):' . $info);
}
return $result();
}
public function throw(\Throwable $throwable): void
{
// Ignore spurious resumes to old dead {main} suspension
if ($this->deadMain) {
return;
}
if (!$this->pending) {
throw $this->error ?? new \Error('Must call suspend() before calling throw()');
}
$this->pending = false;
/** @var \Fiber|null $fiber */
$fiber = $this->fiberRef?->get();
if ($fiber) {
($this->queue)(static function () use ($fiber, $throwable): void {
// The fiber may be destroyed with suspension as part of the GC cycle collector.
if (!$fiber->isTerminated()) {
$fiber->throw($throwable);
}
});
} else {
// Suspend event loop fiber to {main}.
($this->interrupt)(static fn () => throw $throwable);
}
}
private function formatStacktrace(array $trace): string
{
return \implode("\n", \array_map(static function ($e, $i) {
$line = "#{$i} ";
if (isset($e["file"])) {
$line .= "{$e['file']}:{$e['line']} ";
}
if (isset($e["class"], $e["type"])) {
$line .= $e["class"] . $e["type"];
}
return $line . $e["function"] . "()";
}, $trace, \array_keys($trace)));
}
}