Completed
Pull Request — master (#447)
by Marcel
02:47 queued 01:22
created

StartServer::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace BeyondCode\LaravelWebSockets\Console\Commands;
4
5
use BeyondCode\LaravelWebSockets\Contracts\ChannelManager;
6
use BeyondCode\LaravelWebSockets\Facades\StatisticsCollector as StatisticsCollectorFacade;
7
use BeyondCode\LaravelWebSockets\Facades\WebSocketRouter;
8
use BeyondCode\LaravelWebSockets\Server\Loggers\ConnectionLogger;
9
use BeyondCode\LaravelWebSockets\Server\Loggers\HttpLogger;
10
use BeyondCode\LaravelWebSockets\Server\Loggers\WebSocketsLogger;
11
use BeyondCode\LaravelWebSockets\ServerFactory;
12
use Illuminate\Console\Command;
13
use Illuminate\Support\Facades\Cache;
14
use React\EventLoop\Factory as LoopFactory;
15
16
class StartServer extends Command
17
{
18
    /**
19
     * The name and signature of the console command.
20
     *
21
     * @var string
22
     */
23
    protected $signature = 'websockets:serve
24
        {--host=0.0.0.0}
25
        {--port=6001}
26
        {--disable-statistics : Disable the statistics tracking.}
27
        {--statistics-interval= : The amount of seconds to tick between statistics saving.}
28
        {--debug : Forces the loggers to be enabled and thereby overriding the APP_DEBUG setting.}
29
        {--loop : Programatically inject the loop.}
30
    ';
31
32
    /**
33
     * The console command description.
34
     *
35
     * @var string|null
36
     */
37
    protected $description = 'Start the LaravelWebSockets server.';
38
39
    /**
40
     * Get the loop instance.
41
     *
42
     * @var \React\EventLoop\LoopInterface
43
     */
44
    protected $loop;
45
46
    /**
47
     * The Pusher server instance.
48
     *
49
     * @var \Ratchet\Server\IoServer
50
     */
51
    public $server;
52
53
    /**
54
     * Initialize the command.
55
     *
56
     * @return void
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
57
     */
58
    public function __construct()
59
    {
60
        parent::__construct();
61
62
        $this->loop = LoopFactory::create();
63
    }
64
65
    /**
66
     * Run the command.
67
     *
68
     * @return void
69
     */
70
    public function handle()
71
    {
72
        $this->configureLoggers();
73
74
        $this->configureManagers();
75
76
        $this->configureStatistics();
77
78
        $this->configureRestartTimer();
79
80
        $this->configureRoutes();
81
82
        $this->configurePcntlSignal();
83
84
        $this->configurePongTracker();
85
86
        $this->startServer();
87
    }
88
89
    /**
90
     * Configure the loggers used for the console.
91
     *
92
     * @return void
93
     */
94
    protected function configureLoggers()
95
    {
96
        $this->configureHttpLogger();
97
        $this->configureMessageLogger();
98
        $this->configureConnectionLogger();
99
    }
100
101
    /**
102
     * Register the managers that are not resolved
103
     * in the package service provider.
104
     *
105
     * @return void
106
     */
107
    protected function configureManagers()
108
    {
109 View Code Duplication
        $this->laravel->singleton(ChannelManager::class, function () {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
110
            $mode = config('websockets.replication.mode', 'local');
111
112
            $class = config("websockets.replication.modes.{$mode}.channel_manager");
113
114
            return new $class($this->loop);
115
        });
116
    }
117
118
    /**
119
     * Register the Statistics Collectors that
120
     * are not resolved in the package service provider.
121
     *
122
     * @return void
123
     */
124
    protected function configureStatistics()
125
    {
126
        if (! $this->option('disable-statistics')) {
127
            $intervalInSeconds = $this->option('statistics-interval') ?: config('websockets.statistics.interval_in_seconds', 3600);
128
129
            $this->loop->addPeriodicTimer($intervalInSeconds, function () {
130
                $this->line('Saving statistics...');
131
132
                StatisticsCollectorFacade::save();
133
            });
134
        }
135
    }
136
137
    /**
138
     * Configure the restart timer.
139
     *
140
     * @return void
141
     */
142
    public function configureRestartTimer()
143
    {
144
        $this->lastRestart = $this->getLastRestart();
0 ignored issues
show
Bug introduced by
The property lastRestart does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
145
146
        $this->loop->addPeriodicTimer(10, function () {
147
            if ($this->getLastRestart() !== $this->lastRestart) {
148
                $this->triggerSoftShutdown();
149
            }
150
        });
151
    }
152
153
    /**
154
     * Register the routes for the server.
155
     *
156
     * @return void
157
     */
158
    protected function configureRoutes()
159
    {
160
        WebSocketRouter::routes();
161
    }
162
163
    /**
164
     * Configure the PCNTL signals for soft shutdown.
165
     *
166
     * @return void
167
     */
168
    protected function configurePcntlSignal()
169
    {
170
        // When the process receives a SIGTERM or a SIGINT
171
        // signal, it should mark the server as unavailable
172
        // to receive new connections, close the current connections,
173
        // then stopping the loop.
174
175
        $this->loop->addSignal(SIGTERM, function () {
176
            $this->line('Closing existing connections...');
177
178
            $this->triggerSoftShutdown();
179
        });
180
181
        $this->loop->addSignal(SIGINT, function () {
182
            $this->line('Closing existing connections...');
183
184
            $this->triggerSoftShutdown();
185
        });
186
    }
187
188
    /**
189
     * Configure the tracker that will delete
190
     * from the store the connections that.
191
     *
192
     * @return void
193
     */
194
    protected function configurePongTracker()
195
    {
196
        $this->loop->addPeriodicTimer(10, function () {
197
            $this->laravel
198
                ->make(ChannelManager::class)
199
                ->removeObsoleteConnections();
200
        });
201
    }
202
203
    /**
204
     * Configure the HTTP logger class.
205
     *
206
     * @return void
207
     */
208 View Code Duplication
    protected function configureHttpLogger()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
209
    {
210
        $this->laravel->singleton(HttpLogger::class, function () {
211
            return (new HttpLogger($this->output))
212
                ->enable($this->option('debug') ?: config('app.debug'))
213
                ->verbose($this->output->isVerbose());
214
        });
215
    }
216
217
    /**
218
     * Configure the logger for messages.
219
     *
220
     * @return void
221
     */
222 View Code Duplication
    protected function configureMessageLogger()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
223
    {
224
        $this->laravel->singleton(WebSocketsLogger::class, function () {
225
            return (new WebSocketsLogger($this->output))
226
                ->enable($this->option('debug') ?: config('app.debug'))
227
                ->verbose($this->output->isVerbose());
228
        });
229
    }
230
231
    /**
232
     * Configure the connection logger.
233
     *
234
     * @return void
235
     */
236
    protected function configureConnectionLogger()
237
    {
238
        $this->laravel->bind(ConnectionLogger::class, function () {
239
            return (new ConnectionLogger($this->output))
240
                ->enable(config('app.debug'))
241
                ->verbose($this->output->isVerbose());
242
        });
243
    }
244
245
    /**
246
     * Start the server.
247
     *
248
     * @return void
249
     */
250
    protected function startServer()
251
    {
252
        $this->info("Starting the WebSocket server on port {$this->option('port')}...");
253
254
        $this->buildServer();
255
256
        $this->server->run();
257
    }
258
259
    /**
260
     * Build the server instance.
261
     *
262
     * @return void
263
     */
264
    protected function buildServer()
265
    {
266
        $this->server = new ServerFactory(
0 ignored issues
show
Documentation Bug introduced by
It seems like new \BeyondCode\LaravelW... $this->option('port')) of type object<BeyondCode\Larave...bSockets\ServerFactory> is incompatible with the declared type object<Ratchet\Server\IoServer> of property $server.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
267
            $this->option('host'), $this->option('port')
268
        );
269
270
        if ($loop = $this->option('loop')) {
271
            $this->loop = $loop;
0 ignored issues
show
Documentation Bug introduced by
It seems like $loop of type string or array or boolean is incompatible with the declared type object<React\EventLoop\LoopInterface> of property $loop.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
272
        }
273
274
        $this->server = $this->server
275
            ->setLoop($this->loop)
276
            ->withRoutes(WebSocketRouter::getRoutes())
277
            ->setConsoleOutput($this->output)
278
            ->createServer();
279
    }
280
281
    /**
282
     * Get the last time the server restarted.
283
     *
284
     * @return int
285
     */
286
    protected function getLastRestart()
287
    {
288
        return Cache::get(
289
            'beyondcode:websockets:restart', 0
290
        );
291
    }
292
293
    /**
294
     * Trigger a soft shutdown for the process.
295
     *
296
     * @return void
297
     */
298
    protected function triggerSoftShutdown()
299
    {
300
        $channelManager = $this->laravel->make(ChannelManager::class);
301
302
        // Close the new connections allowance on this server.
303
        $channelManager->declineNewConnections();
304
305
        // Get all local connections and close them. They will
306
        // be automatically be unsubscribed from all channels.
307
        $channelManager->getLocalConnections()
308
            ->then(function ($connections) {
309
                foreach ($connections as $connection) {
310
                    $connection->close();
311
                }
312
            })
313
            ->then(function () {
314
                $this->loop->stop();
315
            });
316
    }
317
}
318