-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLoop.php
More file actions
212 lines (180 loc) · 5.42 KB
/
Loop.php
File metadata and controls
212 lines (180 loc) · 5.42 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
<?php
namespace Gt\Async;
use Gt\Async\Timer\Timer;
use Gt\Async\Timer\TimerOrder;
use Gt\Promise\Deferred;
/**
* The core event loop class, used to dispatch all events via different added
* Timer objects.
*
* For efficiency, when the loop's run function is called, timers are sorted
* by their next run time, and the script is delayed by that amount of time,
* rather than wasting CPU cycles in an infinite loop.
*/
class Loop {
/** @var Timer[] */
private array $timerList;
private int $triggerCount;
/** @var callable Function that delays execution by (float $seconds) */
private $sleepFunction;
/** @var callable Function that delivers the current time in milliseconds as a float */
private $timeFunction;
private bool $forever;
private bool $haltWhenAllDeferredComplete;
/** @var Deferred[] */
private array $activeDeferred;
/** @var callable[] */
private array $haltCallbackList;
public function __construct() {
$this->timerList = [];
$this->triggerCount = 0;
$this->sleepFunction = function(float $seconds):void {
usleep((int)($seconds * 1_000_000));
};
$this->timeFunction = function():float {
return microtime(true);
};
$this->haltWhenAllDeferredComplete = false;
$this->activeDeferred = [];
$this->haltCallbackList = [];
}
public function addTimer(Timer $timer):void {
$this->timerList [] = $timer;
}
/**
* Track a Deferred within the loop lifecycle without attaching its
* process callbacks to a Timer.
*
* This is useful for libraries that manage their own work scheduling but
* still want the loop to halt when all tracked Deferred objects complete.
*/
public function trackDeferred(Deferred $deferred):void {
if($this->isDeferredTracked($deferred)) {
return;
}
$deferred->onComplete(
function() use ($deferred) {
$this->removeDeferred($deferred);
});
$this->activeDeferred[] = $deferred;
}
/**
* @deprecated Prefer trackDeferred() when only completion tracking is
* required. This method remains for Deferred objects whose process
* callbacks should still be attached to a Timer.
*/
public function addDeferredToTimer(
Deferred $deferred,
?Timer $timer = null
):void {
$timer = $timer ?? $this->timerList[0];
$this->trackDeferred($deferred);
$deferred->onComplete(
function() use ($deferred, $timer) {
$this->removeDeferredFromTimer(
$deferred,
$timer
);
});
foreach($deferred->getProcessList() as $function) {
$timer->addCallback($function);
}
}
/**
* @deprecated Prefer removeDeferred() when no Timer callbacks were attached
* by addDeferredToTimer().
*/
public function removeDeferredFromTimer(
Deferred $deferred,
?Timer $timer = null
):void {
$timer = $timer ?? $this->timerList[0];
foreach($deferred->getProcessList() as $function) {
$timer->removeCallback($function);
}
$this->removeDeferred($deferred);
}
public function removeDeferred(Deferred $deferred):void {
$activeDeferredIndex = array_search(
$deferred,
$this->activeDeferred,
true
);
if($activeDeferredIndex !== false) {
unset($this->activeDeferred[$activeDeferredIndex]);
}
if($this->haltWhenAllDeferredComplete
&& empty($this->activeDeferred)) {
$this->halt();
}
}
public function setSleepFunction(callable $sleepFunction):void {
$this->sleepFunction = $sleepFunction;
}
public function setTimeFunction(callable $timeFunction):void {
$this->timeFunction = $timeFunction;
}
public function run(bool $forever = true):void {
$this->forever = $forever;
do {
$numTriggered = $this->triggerNextTimers();
$this->triggerCount += $numTriggered;
}
while($numTriggered > 0 && $this->forever);
}
public function halt():void {
$this->forever = false;
foreach($this->haltCallbackList as $callback) {
call_user_func($callback);
}
}
public function haltWhenAllDeferredComplete(
bool $shouldHalt = true
):void {
$this->haltWhenAllDeferredComplete = $shouldHalt;
}
public function addHaltCallback(callable $callback):void {
array_push($this->haltCallbackList, $callback);
}
public function getTriggerCount():int {
return $this->triggerCount;
}
public function waitUntil(float $waitUntilEpoch):void {
$epoch = call_user_func($this->timeFunction);
$diff = $waitUntilEpoch - $epoch;
if($diff <= 0) {
return;
}
call_user_func($this->sleepFunction, $diff);
}
private function triggerNextTimers():int {
$timerOrder = new TimerOrder($this->timerList);
// If there are no more timers to run, return early.
if(count($timerOrder) === 0) {
return 0;
}
// Wait until the first epoch is due, then trigger the timer.
$this->waitUntil($timerOrder->getCurrentEpoch());
$this->trigger($timerOrder->getCurrentTimer());
// Triggering the timer may have caused time to pass so that
// other timers are now due.
$timerOrder->next();
$timerOrderReady = $timerOrder->subset();
$this->executeTimers($timerOrderReady);
// This function will always execute at least 1 timer, it will always wait for
// the next one to trigger, but could have triggered more during the wait for
// the first Timer's execution.
return 1 + count($timerOrderReady);
}
private function trigger(Timer $timer):void {
$timer->tick();
}
private function executeTimers(TimerOrder $timerOrder):void {
foreach($timerOrder as $item) {
$this->trigger($item["timer"]);
}
}
private function isDeferredTracked(Deferred $deferred):bool {
return array_search($deferred, $this->activeDeferred, true) !== false;
}
}