Completed
Pull Request — master (#523)
by Alexandru
14:50
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->startServer();
85
    }
86
87
    /**
88
     * Configure the loggers used for the console.
89
     *
90
     * @return void
91
     */
92
    protected function configureLoggers()
93
    {
94
        $this->configureHttpLogger();
95
        $this->configureMessageLogger();
96
        $this->configureConnectionLogger();
97
    }
98
99
    /**
100
     * Register the managers that are not resolved
101
     * in the package service provider.
102
     *
103
     * @return void
104
     */
105
    protected function configureManagers()
106
    {
107 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...
108
            $mode = config('websockets.replication.mode', 'local');
109
110
            $class = config("websockets.replication.modes.{$mode}.channel_manager");
111
112
            return new $class($this->loop);
113
        });
114
    }
115
116
    /**
117
     * Register the Statistics Collectors that
118
     * are not resolved in the package service provider.
119
     *
120
     * @return void
121
     */
122
    protected function configureStatistics()
123
    {
124
        if (! $this->option('disable-statistics')) {
125
            $intervalInSeconds = $this->option('statistics-interval') ?: config('websockets.statistics.interval_in_seconds', 3600);
126
127
            $this->loop->addPeriodicTimer($intervalInSeconds, function () {
128
                $this->line('Saving statistics...');
129
130
                StatisticsCollectorFacade::save();
131
            });
132
        }
133
    }
134
135
    /**
136
     * Configure the restart timer.
137
     *
138
     * @return void
139
     */
140
    public function configureRestartTimer()
141
    {
142
        $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...
143
144
        $this->loop->addPeriodicTimer(10, function () {
145
            if ($this->getLastRestart() !== $this->lastRestart) {
146
                $this->loop->stop();
147
            }
148
        });
149
    }
150
151
    /**
152
     * Register the routes for the server.
153
     *
154
     * @return void
155
     */
156
    protected function configureRoutes()
157
    {
158
        WebSocketRouter::routes();
159
    }
160
161
    /**
162
     * Configure the PCNTL signals for soft shutdown.
163
     *
164
     * @return void
165
     */
166
    protected function configurePcntlSignal()
167
    {
168
        // When the process receives a SIGTERM or a SIGINT
169
        // signal, it should mark the server as unavailable
170
        // to receive new connections, close the current connections,
171
        // then stopping the loop.
172
173
        $this->loop->addSignal(SIGTERM, function () {
174
            $this->line('Closing existing connections...');
175
176
            $this->triggerSoftShutdown();
177
        });
178
179
        $this->loop->addSignal(SIGINT, function () {
180
            $this->line('Closing existing connections...');
181
182
            $this->triggerSoftShutdown();
183
        });
184
    }
185
186
    /**
187
     * Configure the HTTP logger class.
188
     *
189
     * @return void
190
     */
191 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...
192
    {
193
        $this->laravel->singleton(HttpLogger::class, function () {
194
            return (new HttpLogger($this->output))
195
                ->enable($this->option('debug') ?: config('app.debug'))
196
                ->verbose($this->output->isVerbose());
197
        });
198
    }
199
200
    /**
201
     * Configure the logger for messages.
202
     *
203
     * @return void
204
     */
205 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...
206
    {
207
        $this->laravel->singleton(WebSocketsLogger::class, function () {
208
            return (new WebSocketsLogger($this->output))
209
                ->enable($this->option('debug') ?: config('app.debug'))
210
                ->verbose($this->output->isVerbose());
211
        });
212
    }
213
214
    /**
215
     * Configure the connection logger.
216
     *
217
     * @return void
218
     */
219
    protected function configureConnectionLogger()
220
    {
221
        $this->laravel->bind(ConnectionLogger::class, function () {
222
            return (new ConnectionLogger($this->output))
223
                ->enable(config('app.debug'))
224
                ->verbose($this->output->isVerbose());
225
        });
226
    }
227
228
    /**
229
     * Start the server.
230
     *
231
     * @return void
232
     */
233
    protected function startServer()
234
    {
235
        $this->info("Starting the WebSocket server on port {$this->option('port')}...");
236
237
        $this->buildServer();
238
239
        $this->server->run();
240
    }
241
242
    /**
243
     * Build the server instance.
244
     *
245
     * @return void
246
     */
247
    protected function buildServer()
248
    {
249
        $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...
250
            $this->option('host'), $this->option('port')
251
        );
252
253
        if ($loop = $this->option('loop')) {
254
            $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...
255
        }
256
257
        $this->server = $this->server
258
            ->setLoop($this->loop)
259
            ->withRoutes(WebSocketRouter::getRoutes())
260
            ->setConsoleOutput($this->output)
261
            ->createServer();
262
    }
263
264
    /**
265
     * Get the last time the server restarted.
266
     *
267
     * @return int
268
     */
269
    protected function getLastRestart()
270
    {
271
        return Cache::get(
272
            'beyondcode:websockets:restart', 0
273
        );
274
    }
275
276
    /**
277
     * Trigger a soft shutdown for the process.
278
     *
279
     * @return void
280
     */
281
    protected function triggerSoftShutdown()
282
    {
283
        $channelManager = $this->laravel->make(ChannelManager::class);
284
285
        // Close the new connections allowance on this server.
286
        $channelManager->declineNewConnections();
287
288
        // Get all local connections and close them. They will
289
        // be automatically be unsubscribed from all channels.
290
        $channelManager->getLocalConnections()
291
            ->then(function ($connections) {
292
                foreach ($connections as $connection) {
293
                    $connection->close();
294
                }
295
            })
296
            ->then(function () {
297
                $this->loop->stop();
298
            });
299
    }
300
}
301