GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( b42dfd...ebd3a0 )
by Cees-Jan
13s
created

AsyncClient::setActivityTimeout()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 0
cts 8
cp 0
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 7
nc 3
nop 1
crap 12
1
<?php declare(strict_types=1);
2
3
namespace ApiClients\Client\Pusher;
4
5
use React\Dns\Resolver\Resolver;
6
use React\EventLoop\LoopInterface;
7
use RuntimeException;
8
use Rx\Disposable\CallbackDisposable;
9
use Rx\Observable;
10
use Rx\ObserverInterface;
11
use Rx\Scheduler;
12
use Rx\Websocket\Client as WebsocketClient;
13
use Rx\Websocket\MessageSubject;
14
use Rx\Websocket\WebsocketErrorException;
15
use Throwable;
16
use function React\Promise\reject;
17
use function React\Promise\resolve;
18
19
final class AsyncClient
20
{
21
    const DEFAULT_DELAY = 200;
22
    const NO_ACTIVITY_TIMEOUT = 120;
23
    const NO_PING_RESPONSE_TIMEOUT = 30;
24
25
    protected $noActivityTimeout = self::NO_ACTIVITY_TIMEOUT;
26
27
    /**
28
     * @var Observable\RefCountObservable
29
     */
30
    protected $client;
31
32
    /**
33
     * @var Observable\AnonymousObservable
34
     */
35
    protected $messages;
36
37
    /**
38
     * @var MessageSubject
39
     */
40
    protected $sendSubject;
41
42
    /**
43
     * @var array
44
     */
45
    protected $channels = [];
46
47
    /**
48
     * @var int
49
     */
50
    protected $delay = self::DEFAULT_DELAY;
51
52
    /**
53
     * @internal
54
     */
55 5
    public function __construct(Observable $client)
56
    {
57 5
        $this->messages = $client
58
            // Save this subject for sending stuff
59
            ->do(function (MessageSubject $ms) {
60
                $this->sendSubject = $ms;
61
62
                // Resubscribe to an channels we where subscribed to when disconnected
63
                foreach ($this->channels as $channel => $_) {
64
                    $this->subscribeOnChannel($channel);
65
                }
66 5
            })
67
68
            // Make sure if there is a disconnect or something
69
            // that we unset the sendSubject
70
            ->finally(function () {
71 2
                $this->sendSubject = null;
72 5
            })
73
74
            ->flatMap(function (MessageSubject $ms) {
75
                return $ms;
76 5
            })
77
78
            // This is the ping/timeout functionality
79
            ->flatMapLatest(function ($x) {
80
                // this Observable emits the current value immediately
81
                // if another value comes along, this all gets disposed (because we are using flatMapLatest)
82
                // before the timeouts start get triggered
83
                return Observable::never()
84
                    ->timeout($this->noActivityTimeout * 1000)
85
                    ->catch(function () use ($x) {
86
                        // ping (do something that causes incoming stream to get a message)
87
                        $this->send(['event' => 'pusher:ping']);
88
                        // this timeout will actually timeout with a TimeoutException - causing
89
                        //   everything above this to dispose
90
                        return Observable::never()->timeout(self::NO_PING_RESPONSE_TIMEOUT * 1000);
91
                    })
92
                    ->startWith($x);
93 5
            })
94
95
            // Decode JSON
96 5
            ->_ApiClients_jsonDecode()
97
98
            // Deal with connection established messages
99
            ->flatMap(function (array $message) {
100
                $this->delay = self::DEFAULT_DELAY;
101
102
                $event = Event::createFromMessage($message);
103
104
                if ($event->getEvent() === 'pusher:error') {
105
                    return Observable::fromPromise(reject(
106
                        new PusherErrorException($event->getData()['message'], $event->getData()['code'])
107
                    ));
108
                }
109
110
                if ($event->getEvent() === 'pusher:connection_established') {
111
                    $this->setActivityTimeout($event);
112
                }
113
114
                return Observable::fromPromise(resolve($event));
115 5
            })
116
117
            // Handle connection level and Pusher procotol errors
118
            ->retryWhen(function (Observable $errors) {
119
                return $errors->flatMap(function (Throwable $throwable) {
120 2
                    return $this->handleLowLevelError($throwable);
121 2
                });
122 5
            })
123
124
        // Share client
125 5
        ->share();
126 5
    }
127
128
    /**
129
     * @param  LoopInterface $loop
130
     * @param  string        $app      Application ID
131
     * @param  Resolver      $resolver Optional DNS resolver
132
     * @return AsyncClient
133
     */
134 4
    public static function create(LoopInterface $loop, string $app, Resolver $resolver = null): AsyncClient
135
    {
136
        try {
137
            Scheduler::setAsyncFactory(function () use ($loop) {
138 1
                return new Scheduler\EventLoopScheduler($loop);
0 ignored issues
show
Documentation introduced by
$loop is of type object<React\EventLoop\LoopInterface>, but the function expects a callable.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
139 4
            });
140 3
        } catch (Throwable $t) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
141
        }
142
143 4
        return new self(
144 4
            new WebsocketClient(
145 4
                ApiSettings::createUrl($app),
146 4
                false,
147 4
                [],
148
                $loop,
149 4
                $resolver
150
            )
151
        );
152
    }
153
154
    /**
155
     * Listen on a channel.
156
     *
157
     * @param  string     $channel Channel to listen on
158
     * @return Observable
159
     */
160 2
    public function channel(string $channel): Observable
161
    {
162 2
        if (isset($this->channels[$channel])) {
163
            return $this->channels[$channel];
164
        }
165
166
        // Ensure we only get messages for the given channel
167
        $channelMessages = $this->messages->filter(function (Event $event) use ($channel) {
168
            return $event->getChannel() !== '' && $event->getChannel() === $channel;
169 2
        });
170
171
        $events = Observable::create(function (
172
            ObserverInterface $observer
173
        ) use (
174 2
            $channel,
175 2
            $channelMessages
176
        ) {
177
            $subscription = $channelMessages
178
                ->filter(function (Event $event) {
179
                    return $event->getEvent() !== 'pusher_internal:subscription_succeeded';
180 2
                })
181 2
                ->subscribe($observer);
0 ignored issues
show
Documentation introduced by
$observer is of type object<Rx\ObserverInterface>, but the function expects a callable|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
182
183 2
            $this->subscribeOnChannel($channel);
184
185 2
            return new CallbackDisposable(function () use ($channel, $subscription) {
186
                // Send unsubscribe event
187
                $this->send(['event' => 'pusher:unsubscribe', 'data' => ['channel' => $channel]]);
188
                // Dispose our own subscription to messages
189
                $subscription->dispose();
190
                // Remove our channel from the channel list so we don't resubscribe in case we reconnect
191
                unset($this->channels[$channel]);
192 2
            });
193 2
        });
194
195
        // Share stream amount subscribers to this channel
196 2
        $this->channels[$channel] = $events->share();
197
198 2
        return $this->channels[$channel];
199
    }
200
201
    /**
202
     * Send a message through the client.
203
     *
204
     * @param array $message Message to send, will be json encoded
205
     *
206
     * @return A bool indicating whether or not the connection was active
207
     *           and the given message has been pass onto the connection.
208
     */
209 2
    public function send(array $message): bool
210
    {
211
        // Don't send messages when we aren't connected
212 2
        if ($this->sendSubject ===  null) {
213 2
            return false;
214
        }
215
216
        $this->sendSubject->onNext(json_encode($message));
217
218
        return true;
219
    }
220
221
    /**
222
     *  Handle errors as described at https://pusher.com/docs/pusher_protocol#error-codes.
223
     */
224 2
    private function handleLowLevelError(Throwable $throwable)
225
    {
226 2
        if (!($throwable instanceof WebsocketErrorException) &&
227 2
            !($throwable instanceof RuntimeException) &&
228 2
            !($throwable instanceof PusherErrorException)
229
        ) {
230
            return Observable::fromPromise(reject($throwable));
231
        }
232
233 2
        $code = $throwable->getCode();
234 2
        $pusherError = ($throwable instanceof WebsocketErrorException || $throwable instanceof PusherErrorException);
235
236
        // Errors 4000-4099, don't retry connecting
237 2
        if ($pusherError && $code >= 4000 && $code <= 4099) {
238
            return Observable::fromPromise(reject($throwable));
239
        }
240
241
        // Errors 4100-4199 reconnect after 1 or more seconds, we do it after 1.001 second
242 2
        if ($pusherError && $code >= 4100 && $code <= 4199) {
243
            return Observable::timer(1001);
244
        }
245
246
        // Errors 4200-4299 connection closed by Pusher, reconnect immediately, we wait 0.001 second
247 2
        if ($pusherError && $code >= 4200 && $code <= 4299) {
248
            return Observable::timer(1);
249
        }
250
251 2
        $this->delay *= 2;
252
253 2
        return Observable::timer($this->delay);
254
    }
255
256
    /**
257
     * @param string $channel
258
     */
259 2
    private function subscribeOnChannel(string $channel)
260
    {
261 2
        $this->send(['event' => 'pusher:subscribe', 'data' => ['channel' => $channel]]);
262 2
    }
263
264
    /**
265
     * Get connection activity timeout from connection established event.
266
     *
267
     * @param Event $event
268
     */
269
    private function setActivityTimeout(Event $event)
270
    {
271
        $data = $event->getData();
272
273
        // No activity_timeout found on event
274
        if (!isset($data['activity_timeout'])) {
275
            return;
276
        }
277
278
        // activity_timeout holds zero or invalid value (we don't want to hammer Pusher)
279
        if ((int)$data['activity_timeout'] <= 0) {
280
            return;
281
        }
282
283
        $this->noActivityTimeout = (int)$data['activity_timeout'];
284
    }
285
}
286