forked from revoltphp/event-loop
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAbstractDriver.php
More file actions
664 lines (524 loc) · 21 KB
/
AbstractDriver.php
File metadata and controls
664 lines (524 loc) · 21 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
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
<?php
declare(strict_types=1);
namespace Revolt\EventLoop\Internal;
use Revolt\EventLoop\CallbackType;
use Revolt\EventLoop\Driver;
use Revolt\EventLoop\FiberLocal;
use Revolt\EventLoop\InvalidCallbackError;
use Revolt\EventLoop\Suspension;
use Revolt\EventLoop\UncaughtThrowable;
/**
* Event loop driver which implements all basic operations to allow interoperability.
*
* Callbacks (enabled or new callbacks) MUST immediately be marked as enabled, but only be activated (i.e. callbacks can
* be called) right before the next tick. Callbacks MUST NOT be called in the tick they were enabled.
*
* @internal
*/
abstract class AbstractDriver implements Driver
{
/** @var string Next callback identifier. */
private string $nextId = "a";
private \Fiber $fiber;
private \Fiber $callbackFiber;
private \Closure $errorCallback;
/** @var array<string, DriverCallback> */
private array $callbacks = [];
/** @var array<string, DriverCallback> */
private array $enableQueue = [];
/** @var array<string, DriverCallback> */
private array $enableDeferQueue = [];
/** @var null|\Closure(\Throwable):void */
private ?\Closure $errorHandler = null;
/** @var null|\Closure():mixed */
private ?\Closure $interrupt = null;
private readonly \Closure $interruptCallback;
private readonly \Closure $queueCallback;
/** @var \Closure():(null|\Closure(): mixed) */
private readonly \Closure $runCallback;
private readonly \stdClass $internalSuspensionMarker;
/** @var \SplQueue<array{\Closure, array}> */
private readonly \SplQueue $microtaskQueue;
/** @var \SplQueue<DriverCallback> */
private readonly \SplQueue $callbackQueue;
private bool $idle = false;
private bool $stopped = false;
/** @var \WeakMap<object, \WeakReference<DriverSuspension>> */
private \WeakMap $suspensions;
public function __construct()
{
if (\PHP_VERSION_ID < 80117 || \PHP_VERSION_ID >= 80200 && \PHP_VERSION_ID < 80204) {
// PHP GC is broken on early 8.1 and 8.2 versions, see https://github.com/php/php-src/issues/10496
/** @psalm-suppress RiskyTruthyFalsyComparison */
if (!\getenv('REVOLT_DRIVER_SUPPRESS_ISSUE_10496')) {
throw new \Error('Your version of PHP is affected by serious garbage collector bugs related to fibers. Please upgrade to a newer version of PHP, i.e. >= 8.1.17 or => 8.2.4');
}
}
$this->suspensions = new \WeakMap();
$this->internalSuspensionMarker = new \stdClass();
$this->microtaskQueue = new \SplQueue();
$this->callbackQueue = new \SplQueue();
$this->createLoopFiber();
$this->createCallbackFiber();
$this->createErrorCallback();
/** @psalm-suppress InvalidArgument */
$this->interruptCallback = $this->setInterrupt(...);
$this->queueCallback = $this->queue(...);
$this->runCallback = function (): ?\Closure {
do {
if ($this->fiber->isTerminated()) {
$this->createLoopFiber();
}
$result = $this->fiber->isStarted() ? $this->fiber->resume() : $this->fiber->start();
if ($result) { // Null indicates the loop fiber terminated without suspending.
return $result;
}
} while (\gc_collect_cycles() && !$this->stopped);
return null;
};
}
public function run(): void
{
if ($this->fiber->isRunning()) {
throw new \Error("The event loop is already running");
}
if (\Fiber::getCurrent()) {
throw new \Error(\sprintf("Can't call %s() within a fiber (i.e., outside of {main})", __METHOD__));
}
$lambda = ($this->runCallback)();
if ($lambda) {
$lambda();
throw new \Error(
'Interrupt from event loop must throw an exception: ' . ClosureHelper::getDescription($lambda)
);
}
}
public function stop(): void
{
$this->stopped = true;
}
public function isRunning(): bool
{
return $this->fiber->isRunning() || $this->fiber->isSuspended();
}
public function queue(\Closure $closure, mixed ...$args): void
{
$this->microtaskQueue->enqueue([$closure, $args]);
}
public function defer(\Closure $closure): string
{
$id = $this->nextId;
\PHP_VERSION_ID >= 80300 ? $this->nextId = str_increment($this->nextId) : ++$this->nextId;
$deferCallback = new DeferCallback($id, $closure);
$this->callbacks[$deferCallback->id] = $deferCallback;
$this->enableDeferQueue[$deferCallback->id] = $deferCallback;
return $deferCallback->id;
}
public function delay(float $delay, \Closure $closure): string
{
if ($delay < 0) {
throw new \Error("Delay must be greater than or equal to zero");
}
$id = $this->nextId;
\PHP_VERSION_ID >= 80300 ? $this->nextId = str_increment($this->nextId) : ++$this->nextId;
$timerCallback = new TimerCallback($id, $delay, $closure, $this->now() + $delay);
$this->callbacks[$timerCallback->id] = $timerCallback;
$this->enableQueue[$timerCallback->id] = $timerCallback;
return $timerCallback->id;
}
public function repeat(float $interval, \Closure $closure): string
{
if ($interval < 0) {
throw new \Error("Interval must be greater than or equal to zero");
}
$id = $this->nextId;
\PHP_VERSION_ID >= 80300 ? $this->nextId = str_increment($this->nextId) : ++$this->nextId;
$timerCallback = new TimerCallback($id, $interval, $closure, $this->now() + $interval, true);
$this->callbacks[$timerCallback->id] = $timerCallback;
$this->enableQueue[$timerCallback->id] = $timerCallback;
return $timerCallback->id;
}
public function onReadable(mixed $stream, \Closure $closure): string
{
$id = $this->nextId;
\PHP_VERSION_ID >= 80300 ? $this->nextId = str_increment($this->nextId) : ++$this->nextId;
$streamCallback = new StreamReadableCallback($id, $closure, $stream);
$this->callbacks[$streamCallback->id] = $streamCallback;
$this->enableQueue[$streamCallback->id] = $streamCallback;
return $streamCallback->id;
}
public function onWritable($stream, \Closure $closure): string
{
$id = $this->nextId;
\PHP_VERSION_ID >= 80300 ? $this->nextId = str_increment($this->nextId) : ++$this->nextId;
$streamCallback = new StreamWritableCallback($id, $closure, $stream);
$this->callbacks[$streamCallback->id] = $streamCallback;
$this->enableQueue[$streamCallback->id] = $streamCallback;
return $streamCallback->id;
}
public function onSignal(int $signal, \Closure $closure): string
{
$id = $this->nextId;
\PHP_VERSION_ID >= 80300 ? $this->nextId = str_increment($this->nextId) : ++$this->nextId;
$signalCallback = new SignalCallback($id, $closure, $signal);
$this->callbacks[$signalCallback->id] = $signalCallback;
$this->enableQueue[$signalCallback->id] = $signalCallback;
return $signalCallback->id;
}
public function enable(string $callbackId): string
{
if (!isset($this->callbacks[$callbackId])) {
throw InvalidCallbackError::invalidIdentifier($callbackId);
}
$callback = $this->callbacks[$callbackId];
if ($callback->enabled) {
return $callbackId; // Callback already enabled.
}
$callback->enabled = true;
if ($callback instanceof DeferCallback) {
$this->enableDeferQueue[$callback->id] = $callback;
} elseif ($callback instanceof TimerCallback) {
$callback->expiration = $this->now() + $callback->interval;
$this->enableQueue[$callback->id] = $callback;
} else {
$this->enableQueue[$callback->id] = $callback;
}
return $callbackId;
}
public function cancel(string $callbackId): void
{
$this->disable($callbackId);
unset($this->callbacks[$callbackId]);
}
public function disable(string $callbackId): string
{
if (!isset($this->callbacks[$callbackId])) {
return $callbackId;
}
$callback = $this->callbacks[$callbackId];
if (!$callback->enabled) {
return $callbackId; // Callback already disabled.
}
$callback->enabled = false;
$callback->invokable = false;
$id = $callback->id;
if ($callback instanceof DeferCallback) {
// Callback was only queued to be enabled.
unset($this->enableDeferQueue[$id]);
} elseif (isset($this->enableQueue[$id])) {
// Callback was only queued to be enabled.
unset($this->enableQueue[$id]);
} else {
$this->deactivate($callback);
}
return $callbackId;
}
public function reference(string $callbackId): string
{
if (!isset($this->callbacks[$callbackId])) {
throw InvalidCallbackError::invalidIdentifier($callbackId);
}
$this->callbacks[$callbackId]->referenced = true;
return $callbackId;
}
public function unreference(string $callbackId): string
{
if (!isset($this->callbacks[$callbackId])) {
return $callbackId;
}
$this->callbacks[$callbackId]->referenced = false;
return $callbackId;
}
public function getSuspension(): Suspension
{
$fiber = \Fiber::getCurrent();
// User callbacks are always executed outside the event loop fiber, so this should always be false.
\assert($fiber !== $this->fiber);
// Use queue closure in case of {main}, which can be unset by DriverSuspension after an uncaught exception.
$key = $fiber ?? $this->queueCallback;
$suspension = ($this->suspensions[$key] ?? null)?->get();
if ($suspension) {
return $suspension;
}
$suspension = new DriverSuspension(
$this->runCallback,
$this->queueCallback,
$this->interruptCallback,
$this->suspensions,
);
$this->suspensions[$key] = \WeakReference::create($suspension);
return $suspension;
}
public function setErrorHandler(?\Closure $errorHandler): void
{
$this->errorHandler = $errorHandler;
}
public function getErrorHandler(): ?\Closure
{
return $this->errorHandler;
}
public function __debugInfo(): array
{
// @codeCoverageIgnoreStart
return \array_map(fn (DriverCallback $callback) => [
'type' => $this->getType($callback->id),
'enabled' => $callback->enabled,
'referenced' => $callback->referenced,
], $this->callbacks);
// @codeCoverageIgnoreEnd
}
public function getIdentifiers(): array
{
return \array_keys($this->callbacks);
}
public function getType(string $callbackId): CallbackType
{
$callback = $this->callbacks[$callbackId] ?? throw InvalidCallbackError::invalidIdentifier($callbackId);
return match ($callback::class) {
DeferCallback::class => CallbackType::Defer,
TimerCallback::class => $callback->repeat ? CallbackType::Repeat : CallbackType::Delay,
StreamReadableCallback::class => CallbackType::Readable,
StreamWritableCallback::class => CallbackType::Writable,
SignalCallback::class => CallbackType::Signal,
};
}
public function isEnabled(string $callbackId): bool
{
$callback = $this->callbacks[$callbackId] ?? throw InvalidCallbackError::invalidIdentifier($callbackId);
return $callback->enabled;
}
public function isReferenced(string $callbackId): bool
{
$callback = $this->callbacks[$callbackId] ?? throw InvalidCallbackError::invalidIdentifier($callbackId);
return $callback->referenced;
}
/**
* Activates (enables) all the given callbacks.
*/
abstract protected function activate(array $callbacks): void;
/**
* Dispatches any pending read/write, timer, and signal events.
*/
abstract protected function dispatch(bool $blocking): void;
/**
* Deactivates (disables) the given callback.
*/
abstract protected function deactivate(DriverCallback $callback): void;
final protected function enqueueCallback(DriverCallback $callback): void
{
$this->callbackQueue->enqueue($callback);
$this->idle = false;
}
/**
* Invokes the error handler with the given exception.
*
* @param \Throwable $exception The exception thrown from an event callback.
*/
final protected function error(\Closure $closure, \Throwable $exception): void
{
if ($this->errorHandler === null) {
// Explicitly override the previous interrupt if it exists in this case, hiding the exception is worse
$this->interrupt = static fn () => $exception instanceof UncaughtThrowable
? throw $exception
: throw UncaughtThrowable::throwingCallback($closure, $exception);
return;
}
$fiber = new \Fiber($this->errorCallback);
/** @noinspection PhpUnhandledExceptionInspection */
$fiber->start($this->errorHandler, $exception);
}
/**
* Returns the current event loop time in second increments.
*
* Note this value does not necessarily correlate to wall-clock time, rather the value returned is meant to be used
* in relative comparisons to prior values returned by this method (intervals, expiration calculations, etc.).
*/
abstract protected function now(): float;
private function invokeMicrotasks(): void
{
while (!$this->microtaskQueue->isEmpty()) {
[$callback, $args] = $this->microtaskQueue->dequeue();
try {
// Clear $args to allow garbage collection
$callback(...$args, ...($args = []));
} catch (\Throwable $exception) {
$this->error($callback, $exception);
} finally {
FiberLocal::clear();
}
unset($callback, $args);
if ($this->interrupt) {
/** @noinspection PhpUnhandledExceptionInspection */
\Fiber::suspend($this->internalSuspensionMarker);
}
}
}
/**
* @return bool True if no enabled and referenced callbacks remain in the loop.
*/
private function isEmpty(): bool
{
foreach ($this->callbacks as $callback) {
if ($callback->enabled && $callback->referenced) {
return false;
}
}
return true;
}
/**
* Executes a single tick of the event loop.
*/
private function tick(bool $previousIdle): void
{
$this->activate($this->enableQueue);
foreach ($this->enableQueue as $callback) {
$callback->invokable = true;
}
$this->enableQueue = [];
foreach ($this->enableDeferQueue as $callback) {
$callback->invokable = true;
$this->enqueueCallback($callback);
}
$this->enableDeferQueue = [];
$blocking = $previousIdle
&& !$this->stopped
&& !$this->isEmpty();
if ($blocking) {
$this->invokeCallbacks();
/** @psalm-suppress TypeDoesNotContainType */
if (!empty($this->enableDeferQueue) || !empty($this->enableQueue)) {
$blocking = false;
}
}
/** @psalm-suppress RedundantCondition */
$this->dispatch($blocking);
}
private function invokeCallbacks(): void
{
while (!$this->microtaskQueue->isEmpty() || !$this->callbackQueue->isEmpty()) {
/** @noinspection PhpUnhandledExceptionInspection */
$yielded = $this->callbackFiber->isStarted()
? $this->callbackFiber->resume()
: $this->callbackFiber->start();
if ($yielded !== $this->internalSuspensionMarker) {
$this->createCallbackFiber();
}
if ($this->interrupt) {
$this->invokeInterrupt();
}
}
}
/**
* @param \Closure():mixed $interrupt
*/
private function setInterrupt(\Closure $interrupt): void
{
\assert($this->interrupt === null);
$this->interrupt = $interrupt;
}
private function invokeInterrupt(): void
{
\assert($this->interrupt !== null);
$interrupt = $this->interrupt;
$this->interrupt = null;
/** @noinspection PhpUnhandledExceptionInspection */
\Fiber::suspend($interrupt);
}
private function createLoopFiber(): void
{
$this->fiber = new \Fiber(function (): void {
$this->stopped = false;
// Invoke microtasks if we have some
$this->invokeCallbacks();
/** @psalm-suppress RedundantCondition $this->stopped may be changed by $this->invokeCallbacks(). */
while (!$this->stopped) {
if ($this->interrupt) {
$this->invokeInterrupt();
}
if ($this->isEmpty()) {
return;
}
$previousIdle = $this->idle;
$this->idle = true;
$this->tick($previousIdle);
$this->invokeCallbacks();
}
});
}
private function createCallbackFiber(): void
{
$this->callbackFiber = new \Fiber(function (): void {
do {
$this->invokeMicrotasks();
while (!$this->callbackQueue->isEmpty()) {
/** @var DriverCallback $callback */
$callback = $this->callbackQueue->dequeue();
if (!isset($this->callbacks[$callback->id]) || !$callback->invokable) {
unset($callback);
continue;
}
if ($callback instanceof DeferCallback) {
$this->cancel($callback->id);
} elseif ($callback instanceof TimerCallback) {
if (!$callback->repeat) {
$this->cancel($callback->id);
} else {
// Disable and re-enable, so it's not executed repeatedly in the same tick
// See https://github.com/amphp/amp/issues/131
$this->disable($callback->id);
$this->enable($callback->id);
}
}
try {
$result = match (true) {
$callback instanceof StreamCallback => ($callback->closure)(
$callback->id,
$callback->stream
),
$callback instanceof SignalCallback => ($callback->closure)(
$callback->id,
$callback->signal
),
default => ($callback->closure)($callback->id),
};
if ($result !== null) {
throw InvalidCallbackError::nonNullReturn($callback->id, $callback->closure);
}
} catch (\Throwable $exception) {
$this->error($callback->closure, $exception);
} finally {
FiberLocal::clear();
}
unset($callback);
if ($this->interrupt) {
/** @noinspection PhpUnhandledExceptionInspection */
\Fiber::suspend($this->internalSuspensionMarker);
}
$this->invokeMicrotasks();
}
/** @noinspection PhpUnhandledExceptionInspection */
\Fiber::suspend($this->internalSuspensionMarker);
} while (true);
});
}
private function createErrorCallback(): void
{
$this->errorCallback = function (\Closure $errorHandler, \Throwable $exception): void {
try {
$errorHandler($exception);
} catch (\Throwable $exception) {
$this->interrupt = static fn () => $exception instanceof UncaughtThrowable
? throw $exception
: throw UncaughtThrowable::throwingErrorHandler($errorHandler, $exception);
}
};
}
final public function __serialize(): never
{
throw new \Error(__CLASS__ . ' does not support serialization');
}
final public function __unserialize(array $data): never
{
throw new \Error(__CLASS__ . ' does not support deserialization');
}
}