summaryrefslogtreecommitdiff
path: root/vendor/aws/aws-sdk-php/src/Waiter.php
blob: 74b2480131f3bb49df3514521b9d0d9941a42b93 (plain)
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
<?php
namespace Aws;

use Aws\Exception\AwsException;
use GuzzleHttp\Promise\Coroutine;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Promise\PromisorInterface;
use GuzzleHttp\Promise\RejectedPromise;

/**
 * "Waiters" are associated with an AWS resource (e.g., EC2 instance), and poll
 * that resource and until it is in a particular state.

 * The Waiter object produces a promise that is either a.) resolved once the
 * waiting conditions are met, or b.) rejected if the waiting conditions cannot
 * be met or has exceeded the number of allowed attempts at meeting the
 * conditions. You can use waiters in a blocking or non-blocking way, depending
 * on whether you call wait() on the promise.

 * The configuration for the waiter must include information about the operation
 * and the conditions for wait completion.
 */
class Waiter implements PromisorInterface
{
    /** @var AwsClientInterface Client used to execute each attempt. */
    private $client;

    /** @var string Name of the waiter. */
    private $name;

    /** @var array Params to use with each attempt operation. */
    private $args;

    /** @var array Waiter configuration. */
    private $config;

    /** @var array Default configuration options. */
    private static $defaults = ['initDelay' => 0, 'before' => null];

    /** @var array Required configuration options. */
    private static $required = [
        'acceptors',
        'delay',
        'maxAttempts',
        'operation',
    ];

    /**
     * The array of configuration options include:
     *
     * - acceptors: (array) Array of acceptor options
     * - delay: (int) Number of seconds to delay between attempts
     * - maxAttempts: (int) Maximum number of attempts before failing
     * - operation: (string) Name of the API operation to use for polling
     * - before: (callable) Invoked before attempts. Accepts command and tries.
     *
     * @param AwsClientInterface $client Client used to execute commands.
     * @param string             $name   Waiter name.
     * @param array              $args   Command arguments.
     * @param array              $config Waiter config that overrides defaults.
     *
     * @throws \InvalidArgumentException if the configuration is incomplete.
     */
    public function __construct(
        AwsClientInterface $client,
        $name,
        array $args = [],
        array $config = []
    ) {
        $this->client = $client;
        $this->name = $name;
        $this->args = $args;

        // Prepare and validate config.
        $this->config = $config + self::$defaults;
        foreach (self::$required as $key) {
            if (!isset($this->config[$key])) {
                throw new \InvalidArgumentException(
                    'The provided waiter configuration was incomplete.'
                );
            }
        }
        if ($this->config['before'] && !is_callable($this->config['before'])) {
            throw new \InvalidArgumentException(
                'The provided "before" callback is not callable.'
            );
        }
    }

    /**
     * @return Coroutine
     */
    public function promise(): PromiseInterface
    {
        return Coroutine::of(function () {
            $name = $this->config['operation'];
            for ($state = 'retry', $attempt = 1; $state === 'retry'; $attempt++) {
                // Execute the operation.
                $args = $this->getArgsForAttempt($attempt);
                $command = $this->client->getCommand($name, $args);
                try {
                    if ($this->config['before']) {
                        $this->config['before']($command, $attempt);
                    }
                    $result = (yield $this->client->executeAsync($command));
                } catch (AwsException $e) {
                    $result = $e;
                }

                // Determine the waiter's state and what to do next.
                $state = $this->determineState($result);
                if ($state === 'success') {
                    yield $command;
                } elseif ($state === 'failed') {
                    $msg = "The {$this->name} waiter entered a failure state.";
                    if ($result instanceof \Exception) {
                        $msg .= ' Reason: ' . $result->getMessage();
                    }
                    yield new RejectedPromise(new \RuntimeException($msg));
                } elseif ($state === 'retry'
                    && $attempt >= $this->config['maxAttempts']
                ) {
                    $state = 'failed';
                    yield new RejectedPromise(new \RuntimeException(
                        "The {$this->name} waiter failed after attempt #{$attempt}."
                    ));
                }
            }
        });
    }

    /**
     * Gets the operation arguments for the attempt, including the delay.
     *
     * @param $attempt Number of the current attempt.
     *
     * @return mixed integer
     */
    private function getArgsForAttempt($attempt)
    {
        $args = $this->args;

        // Determine the delay.
        $delay = ($attempt === 1)
            ? $this->config['initDelay']
            : $this->config['delay'];
        if (is_callable($delay)) {
            $delay = $delay($attempt);
        }

        // Set the delay. (Note: handlers except delay in milliseconds.)
        if (!isset($args['@http'])) {
            $args['@http'] = [];
        }
        $args['@http']['delay'] = $delay * 1000;

        return $args;
    }

    /**
     * Determines the state of the waiter attempt, based on the result of
     * polling the resource. A waiter can have the state of "success", "failed",
     * or "retry".
     *
     * @param mixed $result
     *
     * @return string Will be "success", "failed", or "retry"
     */
    private function determineState($result)
    {
        foreach ($this->config['acceptors'] as $acceptor) {
            $matcher = 'matches' . ucfirst($acceptor['matcher']);
            if ($this->{$matcher}($result, $acceptor)) {
                return $acceptor['state'];
            }
        }

        return $result instanceof \Exception ? 'failed' : 'retry';
    }

    /**
     * @param Result $result   Result or exception.
     * @param array  $acceptor Acceptor configuration being checked.
     *
     * @return bool
     */
    private function matchesPath($result, array $acceptor)
    {
        return !($result instanceof ResultInterface)
            ? false
            : $acceptor['expected'] == $result->search($acceptor['argument']);
    }

    /**
     * @param Result $result   Result or exception.
     * @param array  $acceptor Acceptor configuration being checked.
     *
     * @return bool
     */
    private function matchesPathAll($result, array $acceptor)
    {
        if (!($result instanceof ResultInterface)) {
            return false;
        }

        $actuals = $result->search($acceptor['argument']) ?: [];
        foreach ($actuals as $actual) {
            if ($actual != $acceptor['expected']) {
                return false;
            }
        }

        return true;
    }

    /**
     * @param Result $result   Result or exception.
     * @param array  $acceptor Acceptor configuration being checked.
     *
     * @return bool
     */
    private function matchesPathAny($result, array $acceptor)
    {
        if (!($result instanceof ResultInterface)) {
            return false;
        }

        $actuals = $result->search($acceptor['argument']) ?: [];
        return in_array($acceptor['expected'], $actuals);
    }

    /**
     * @param Result $result   Result or exception.
     * @param array  $acceptor Acceptor configuration being checked.
     *
     * @return bool
     */
    private function matchesStatus($result, array $acceptor)
    {
        if ($result instanceof ResultInterface) {
            return $acceptor['expected'] == $result['@metadata']['statusCode'];
        }

        if ($result instanceof AwsException && $response = $result->getResponse()) {
            return $acceptor['expected'] == $response->getStatusCode();
        }

        return false;
    }

    /**
     * @param Result $result   Result or exception.
     * @param array  $acceptor Acceptor configuration being checked.
     *
     * @return bool
     */
    private function matchesError($result, array $acceptor)
    {
        if ($result instanceof AwsException) {
            return $result->isConnectionError()
                || $result->getAwsErrorCode() == $acceptor['expected'];
        }

        return false;
    }
}