vendor/guzzlehttp/promises/src/EachPromise.php

298 lines · 9313 bytes

  1<?php
  2
  3declare(strict_types=1);
  4
  5namespace GuzzleHttp\Promise;
  6
  7/**
  8 * Represents a promise that iterates over many promises and invokes
  9 * side-effect functions in the process.
 10 *
 11 * @final
 12 */
 13class EachPromise implements PromisorInterface
 14{
 15    private $pending = [];
 16
 17    private $nextPendingIndex = 0;
 18
 19    /** @var \Iterator|null */
 20    private $iterable;
 21
 22    /** @var callable|int|null */
 23    private $concurrency;
 24
 25    /** @var callable|null */
 26    private $onFulfilled;
 27
 28    /** @var callable|null */
 29    private $onRejected;
 30
 31    /** @var Promise|null */
 32    private $aggregate;
 33
 34    /** @var bool|null */
 35    private $mutex;
 36
 37    /** @var bool */
 38    private $stepWhileLocked = false;
 39
 40    /**
 41     * Configuration hash can include the following key value pairs:
 42     *
 43     * - fulfilled: (callable) Invoked when a promise fulfills. The function
 44     *   is invoked with three arguments: the fulfillment value, the index
 45     *   position from the iterable list of the promise, and the aggregate
 46     *   promise that manages all of the promises. The aggregate promise may
 47     *   be resolved from within the callback to short-circuit the promise.
 48     * - rejected: (callable) Invoked when a promise is rejected. The
 49     *   function is invoked with three arguments: the rejection reason, the
 50     *   index position from the iterable list of the promise, and the
 51     *   aggregate promise that manages all of the promises. The aggregate
 52     *   promise may be resolved from within the callback to short-circuit
 53     *   the promise.
 54     * - concurrency: (integer) Pass this configuration option to limit the
 55     *   allowed number of outstanding concurrently executing promises,
 56     *   creating a capped pool of promises. There is no limit by default.
 57     *
 58     * @param mixed $iterable Promises or values to iterate.
 59     * @param array $config   Configuration options
 60     */
 61    public function __construct($iterable, array $config = [])
 62    {
 63        if (!is_iterable($iterable)) {
 64            \trigger_deprecation(
 65                'guzzlehttp/promises',
 66                '2.5',
 67                'Passing a non-iterable to %s::%s() is deprecated; guzzlehttp/promises 3.0 will require an iterable.',
 68                __CLASS__,
 69                __FUNCTION__
 70            );
 71
 72            $iterable = [$iterable];
 73        }
 74
 75        $this->iterable = Create::iterFor($iterable);
 76
 77        if (isset($config['concurrency'])) {
 78            $this->concurrency = $config['concurrency'];
 79        }
 80
 81        if (isset($config['fulfilled'])) {
 82            $this->onFulfilled = $config['fulfilled'];
 83        }
 84
 85        if (isset($config['rejected'])) {
 86            $this->onRejected = $config['rejected'];
 87        }
 88    }
 89
 90    /** @psalm-suppress InvalidNullableReturnType */
 91    public function promise(): PromiseInterface
 92    {
 93        if ($this->aggregate) {
 94            return $this->aggregate;
 95        }
 96
 97        try {
 98            $this->createPromise();
 99            /** @psalm-assert Promise $this->aggregate */
100            $this->iterable->rewind();
101            $this->refillPending();
102            if (!$this->pending) {
103                Utils::queue()->add(function (): void {
104                    if (!$this->aggregate || State::isSettled($this->aggregate)) {
105                        return;
106                    }
107
108                    try {
109                        $this->checkIfFinished();
110                    } catch (\Throwable $e) {
111                        $this->aggregate->reject($e);
112                    }
113                });
114            }
115        } catch (\Throwable $e) {
116            $this->aggregate->reject($e);
117        }
118
119        /**
120         * @psalm-suppress NullableReturnStatement
121         */
122        return $this->aggregate;
123    }
124
125    private function createPromise(): void
126    {
127        $this->mutex = false;
128        $this->aggregate = new Promise(function (): void {
129            while (true) {
130                if ($this->checkIfFinished()) {
131                    return;
132                }
133                reset($this->pending);
134                // Consume a potentially fluctuating list of promises while
135                // ensuring that indexes are maintained (precluding array_shift).
136                while ($promise = current($this->pending)) {
137                    next($this->pending);
138                    $promise->wait();
139                    if (State::isSettled($this->aggregate)) {
140                        return;
141                    }
142                }
143                // Refill and re-sweep; give up only when nothing remains.
144                $this->refillPending();
145                if (State::isSettled($this->aggregate) || !$this->pending) {
146                    return;
147                }
148            }
149        });
150
151        // Clear the references when the promise is resolved.
152        $clearFn = function (): void {
153            $this->iterable = $this->concurrency = $this->pending = null;
154            $this->onFulfilled = $this->onRejected = null;
155            $this->nextPendingIndex = 0;
156        };
157
158        $this->aggregate->then($clearFn, $clearFn);
159    }
160
161    private function refillPending(): void
162    {
163        if (!$this->concurrency) {
164            // Add all pending promises.
165            while ($this->addPending() && $this->advanceIterator()) {
166            }
167
168            return;
169        }
170
171        // Add only up to N pending promises.
172        $concurrency = is_callable($this->concurrency)
173            ? ($this->concurrency)(count($this->pending))
174            : $this->concurrency;
175        // The callable can settle the aggregate; admit nothing more.
176        if (State::isSettled($this->aggregate)) {
177            return;
178        }
179        $concurrency = max($concurrency - count($this->pending), 0);
180        // Concurrency may be set to 0 to disallow new promises.
181        if (!$concurrency) {
182            return;
183        }
184        // Add the first pending promise.
185        $this->addPending();
186        // Note this is special handling for concurrency=1 so that we do
187        // not advance the iterator after adding the first promise. This
188        // helps work around issues with generators that might not have the
189        // next value to yield until promise callbacks are called.
190        while (--$concurrency
191            && $this->advanceIterator()
192            && $this->addPending()) {
193        }
194    }
195
196    private function addPending(): bool
197    {
198        if (!$this->iterable || !$this->iterable->valid()) {
199            return false;
200        }
201
202        $promise = Create::promiseFor($this->iterable->current());
203        $key = $this->iterable->key();
204
205        // Iterable keys may not be unique, so we use a counter to
206        // guarantee uniqueness
207        $idx = $this->nextPendingIndex++;
208
209        $this->pending[$idx] = $promise->then(
210            function ($value) use ($idx, $key): void {
211                if ($this->onFulfilled) {
212                    ($this->onFulfilled)(
213                        $value,
214                        $key,
215                        $this->aggregate
216                    );
217                }
218                $this->step($idx);
219            },
220            function ($reason) use ($idx, $key): void {
221                if ($this->onRejected) {
222                    ($this->onRejected)(
223                        $reason,
224                        $key,
225                        $this->aggregate
226                    );
227                }
228                $this->step($idx);
229            }
230        );
231
232        return true;
233    }
234
235    private function advanceIterator(): bool
236    {
237        // Place a lock on the iterator so that we ensure to not recurse,
238        // preventing fatal generator errors.
239        if ($this->mutex) {
240            $this->stepWhileLocked = true;
241
242            return false;
243        }
244
245        $this->mutex = true;
246
247        try {
248            $this->iterable->next();
249            $this->mutex = false;
250        } catch (\Throwable $e) {
251            $this->aggregate->reject($e);
252            $this->mutex = false;
253
254            return false;
255        }
256
257        // Run the completion check that locked steps skipped.
258        if ($this->stepWhileLocked) {
259            $this->stepWhileLocked = false;
260            if (!State::isSettled($this->aggregate)) {
261                $this->checkIfFinished();
262            }
263        }
264
265        return true;
266    }
267
268    private function step(int $idx): void
269    {
270        // If the promise was already resolved, then ignore this step.
271        if (State::isSettled($this->aggregate)) {
272            return;
273        }
274
275        unset($this->pending[$idx]);
276
277        // Only refill pending promises if we are not locked, preventing the
278        // EachPromise to recursively invoke the provided iterator, which
279        // cause a fatal error: "Cannot resume an already running generator"
280        if ($this->advanceIterator() && !$this->checkIfFinished()) {
281            // Add more pending promises if possible.
282            $this->refillPending();
283        }
284    }
285
286    /** @phpstan-impure */
287    private function checkIfFinished(): bool
288    {
289        if (!$this->pending && !$this->iterable->valid()) {
290            // Resolve the promise if there's nothing left to do.
291            $this->aggregate->resolve(null);
292
293            return true;
294        }
295
296        return false;
297    }
298}