-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasync.php
More file actions
208 lines (182 loc) · 5.63 KB
/
async.php
File metadata and controls
208 lines (182 loc) · 5.63 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
<?php
/**
* Structured concurrency helpers for FrankenAsync.
*
* Composable generators on top of Script::async() and Future.
* No Swow, no coroutines — just plain PHP generators and threads.
*/
namespace Frankenphp\Async;
use Frankenphp\Script;
use Frankenphp\Async\Future;
/**
* Race multiple futures — first wins, rest get cancelled.
*
* Usage:
* $result = yield from race([
* (new Script('primary.php'))->async(),
* (new Script('fallback.php'))->async(),
* ], "5s");
*
* @param Future[] $tasks Array of Future objects (already dispatched)
* @param string $timeout Go-style duration string ("5s", "500ms")
* @return \Generator Yields the result of the first completed task
*/
function race(array $tasks, string $timeout = "30s"): \Generator
{
$result = Future::awaitAny($tasks, $timeout);
// Cancel remaining tasks
foreach ($tasks as $task) {
if ($task->getStatus() === 'running') {
$task->cancel();
}
}
yield $result;
}
/**
* Retry a callable with exponential backoff.
*
* The callable must return a Future (via Script::async()).
*
* Usage:
* $result = yield from retry(3,
* fn() => (new Script('flaky.php'))->async(['id' => 1]),
* "1s", 2.0);
*
* @param int $attempts Maximum number of attempts
* @param callable(): Future $callable Returns a Future to await
* @param string $delay Initial delay between retries ("100ms", "1s")
* @param float $multiplier Backoff multiplier (default: 2.0)
* @return \Generator Yields the successful result
* @throws \RuntimeException If all attempts fail
*/
function retry(
int $attempts,
callable $callable,
string $delay = "100ms",
float $multiplier = 2.0,
): \Generator {
$delayMs = (int)(duration($delay) * 1000);
$lastError = null;
for ($attempt = 1; $attempt <= $attempts; $attempt++) {
$task = $callable();
try {
$result = $task->await("30s");
if ($task->getError() === null) {
yield $result;
return;
}
$lastError = $task->getError();
} catch (\Throwable $e) {
$lastError = $e->getMessage();
}
if ($attempt < $attempts && $delayMs > 0) {
usleep($delayMs * 1000);
$delayMs = (int)($delayMs * $multiplier);
}
}
throw new \RuntimeException("Failed after $attempts attempts: $lastError");
}
/**
* Execute callables in parallel with a concurrency limit.
*
* Each callable must return a Future (via Script::async()).
* Results are returned in the same order as input.
*
* Usage:
* $results = yield from parallel($callables, concurrency: 5);
*
* @param array<callable(): Future> $callables Array of callables returning Futures
* @param int $concurrency Max concurrent tasks (sliding window)
* @param string $timeout Timeout per batch
* @return \Generator Yields array of results in input order
*/
function parallel(
array $callables,
int $concurrency = 10,
string $timeout = "30s",
): \Generator {
if (empty($callables)) {
yield [];
return;
}
$results = [];
foreach (array_chunk($callables, $concurrency, true) as $chunk) {
$tasks = [];
foreach ($chunk as $index => $callable) {
$tasks[$index] = $callable();
}
$batchResults = Future::awaitAll(array_values($tasks), $timeout);
$i = 0;
foreach ($tasks as $index => $task) {
$results[$index] = $batchResults[$i++];
}
}
yield $results;
}
/**
* Throttle tasks into batches — yields results as each batch completes.
*
* Generator-based: streams results instead of collecting everything into memory.
*
* Usage:
* foreach (throttle($ids, 'task.php', batch: 50) as $result) {
* process($result);
* }
*
* @param array $ids Array of IDs to process
* @param string $script PHP script to execute for each ID
* @param array $params Base parameters (id is added automatically)
* @param int $batch Batch size (tasks per round)
* @param string $timeout Timeout per batch
* @return \Generator Yields individual results as batches complete
*/
function throttle(
array $ids,
string $script,
array $params = [],
int $batch = 10,
string $timeout = "30s",
): \Generator {
foreach (array_chunk($ids, $batch) as $chunk) {
$tasks = [];
foreach ($chunk as $id) {
$tasks[] = (new Script($script))->async(array_merge($params, ['id' => $id]));
}
$results = Future::awaitAll($tasks, $timeout);
foreach ($results as $result) {
yield $result;
}
}
}
/**
* Parse a Go-style duration string to seconds.
*
* @internal
* @param string $duration Duration string ("100ms", "1s", "5m", "1h30m")
* @return float Duration in seconds
*/
function duration(string $duration): float
{
if (is_numeric($duration)) {
return (float) $duration;
}
$duration = trim($duration);
$total = 0.0;
if (!preg_match_all('/([0-9]*\.?[0-9]+)(ns|us|µs|ms|s|m|h)/i', $duration, $matches, PREG_SET_ORDER)) {
throw new \InvalidArgumentException("Invalid duration format: '$duration'");
}
foreach ($matches as $match) {
$value = (float) $match[1];
$unit = strtolower($match[2]);
$total += match ($unit) {
'ns' => $value / 1_000_000_000,
'us', 'µs' => $value / 1_000_000,
'ms' => $value / 1_000,
's' => $value,
'm' => $value * 60,
'h' => $value * 3600,
default => throw new \InvalidArgumentException("Unknown duration unit: '$unit'"),
};
}
return $total;
}