-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathDriverSuspension.php
More file actions
106 lines (87 loc) · 2.97 KB
/
DriverSuspension.php
File metadata and controls
106 lines (87 loc) · 2.97 KB
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
<?php
namespace Revolt\EventLoop\Internal;
use Revolt\EventLoop\Driver;
use Revolt\EventLoop\Suspension;
/**
* @internal
*/
final class DriverSuspension implements Suspension
{
private ?\Fiber $fiber;
private \Fiber $scheduler;
private Driver $driver;
private bool $pending = false;
private ?\FiberError $error = null;
/** @var callable */
private $interrupt;
/**
* @param Driver $driver
* @param \Fiber $scheduler
* @param callable $interrupt
*
* @internal
*/
public function __construct(Driver $driver, \Fiber $scheduler, callable $interrupt)
{
$this->driver = $driver;
$this->scheduler = $scheduler;
$this->interrupt = $interrupt;
$this->fiber = \Fiber::getCurrent();
// User callbacks are always executed outside the event loop fiber, so this should always be false.
\assert($this->fiber !== $this->scheduler);
}
public function throw(\Throwable $throwable): void
{
if (!$this->pending) {
throw $this->error ?? new \Error('Must call suspend() before calling throw()');
}
$this->pending = false;
if ($this->fiber) {
$this->driver->queue([$this->fiber, 'throw'], $throwable);
} else {
// Suspend event loop fiber to {main}.
($this->interrupt)(static fn () => throw $throwable);
}
}
public function resume(mixed $value = null): void
{
if (!$this->pending) {
throw $this->error ?? new \Error('Must call suspend() before calling resume()');
}
$this->pending = false;
if ($this->fiber) {
$this->driver->queue([$this->fiber, 'resume'], $value);
} else {
// Suspend event loop fiber to {main}.
($this->interrupt)(static fn () => $value);
}
}
public function suspend(): mixed
{
if ($this->pending) {
throw new \Error('Must call resume() or throw() before calling suspend() again');
}
if ($this->fiber !== \Fiber::getCurrent()) {
throw new \Error('Must not call suspend() from another fiber');
}
$this->pending = true;
// Awaiting from within a fiber.
if ($this->fiber) {
try {
return \Fiber::suspend();
} catch (\FiberError $exception) {
$this->pending = false;
$this->error = $exception;
throw $exception;
}
}
// Awaiting from {main}.
$lambda = $this->scheduler->isStarted() ? $this->scheduler->resume() : $this->scheduler->start();
/** @psalm-suppress RedundantCondition $this->pending should be changed when resumed. */
if ($this->pending) {
// Should only be true if the event loop exited without resolving the promise.
throw new \Error('Scheduler suspended or exited unexpectedly');
}
return $lambda();
}
}