Completed
Pull Request — master (#140)
by
unknown
01:21
created

StartWebSocketServer::configurePubSubReplication()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.7998
c 0
b 0
f 0
cc 3
nc 3
nop 0
1
<?php
2
3
namespace BeyondCode\LaravelWebSockets\Console;
4
5
use React\Socket\Connector;
6
use Clue\React\Buzz\Browser;
7
use Illuminate\Console\Command;
8
use React\Dns\Config\Config as DnsConfig;
9
use React\Dns\Resolver\ResolverInterface;
10
use React\EventLoop\Factory as LoopFactory;
11
use React\Dns\Resolver\Factory as DnsFactory;
12
use BeyondCode\LaravelWebSockets\Statistics\DnsResolver;
13
use BeyondCode\LaravelWebSockets\Facades\StatisticsLogger;
14
use BeyondCode\LaravelWebSockets\Facades\WebSocketsRouter;
15
use BeyondCode\LaravelWebSockets\PubSub\Redis\RedisClient;
16
use BeyondCode\LaravelWebSockets\Server\Logger\HttpLogger;
17
use BeyondCode\LaravelWebSockets\PubSub\ReplicationInterface;
18
use BeyondCode\LaravelWebSockets\Server\WebSocketServerFactory;
19
use BeyondCode\LaravelWebSockets\Server\Logger\ConnectionLogger;
20
use BeyondCode\LaravelWebSockets\Server\Logger\WebsocketsLogger;
21
use BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager;
22
use BeyondCode\LaravelWebSockets\Statistics\Logger\HttpStatisticsLogger;
23
use BeyondCode\LaravelWebSockets\Statistics\Logger\StatisticsLogger as StatisticsLoggerInterface;
24
25
class StartWebSocketServer extends Command
26
{
27
    protected $signature = 'websockets:serve {--host=0.0.0.0} {--port=6001} {--debug : Forces the loggers to be enabled and thereby overriding the app.debug config setting } ';
28
29
    protected $description = 'Start the Laravel WebSocket Server';
30
31
    /** @var \React\EventLoop\LoopInterface */
32
    protected $loop;
33
34
    public function __construct()
35
    {
36
        parent::__construct();
37
38
        $this->loop = LoopFactory::create();
39
    }
40
41
    public function handle()
42
    {
43
        $this
44
            ->configureStatisticsLogger()
45
            ->configureHttpLogger()
46
            ->configureMessageLogger()
47
            ->configureConnectionLogger()
48
            ->registerEchoRoutes()
49
            ->registerCustomRoutes()
50
            ->configurePubSubReplication()
51
            ->startWebSocketServer();
52
    }
53
54
    protected function configureStatisticsLogger()
55
    {
56
        $connector = new Connector($this->loop, [
57
            'dns' => $this->getDnsResolver(),
58
            'tls' => [
59
                'verify_peer' => config('app.env') === 'production',
60
                'verify_peer_name' => config('app.env') === 'production',
61
            ],
62
        ]);
63
64
        $browser = new Browser($this->loop, $connector);
65
66
        $this->laravel->singleton(StatisticsLoggerInterface::class, function () use ($browser) {
67
            return new HttpStatisticsLogger($this->laravel->make(ChannelManager::class), $browser);
68
        });
69
70
        $this->loop->addPeriodicTimer(config('websockets.statistics.interval_in_seconds'), function () {
71
            StatisticsLogger::save();
72
        });
73
74
        return $this;
75
    }
76
77 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...
78
    {
79
        $this->laravel->singleton(HttpLogger::class, function () {
80
            return (new HttpLogger($this->output))
81
                ->enable($this->option('debug') ?: config('app.debug'))
82
                ->verbose($this->output->isVerbose());
83
        });
84
85
        return $this;
86
    }
87
88 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...
89
    {
90
        $this->laravel->singleton(WebsocketsLogger::class, function () {
91
            return (new WebsocketsLogger($this->output))
92
                ->enable($this->option('debug') ?: config('app.debug'))
93
                ->verbose($this->output->isVerbose());
94
        });
95
96
        return $this;
97
    }
98
99 View Code Duplication
    protected function configureConnectionLogger()
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...
100
    {
101
        $this->laravel->bind(ConnectionLogger::class, function () {
102
            return (new ConnectionLogger($this->output))
103
                ->enable(config('app.debug'))
104
                ->verbose($this->output->isVerbose());
105
        });
106
107
        return $this;
108
    }
109
110
    protected function registerEchoRoutes()
111
    {
112
        WebSocketsRouter::echo();
113
114
        return $this;
115
    }
116
117
    protected function registerCustomRoutes()
118
    {
119
        WebSocketsRouter::customRoutes();
120
121
        return $this;
122
    }
123
124
    protected function startWebSocketServer()
125
    {
126
        $this->info("Starting the WebSocket server on port {$this->option('port')}...");
127
128
        $routes = WebSocketsRouter::getRoutes();
129
130
        /* 🛰 Start the server 🛰  */
131
        (new WebSocketServerFactory())
132
            ->setLoop($this->loop)
133
            ->useRoutes($routes)
134
            ->setHost($this->option('host'))
135
            ->setPort($this->option('port'))
136
            ->setConsoleOutput($this->output)
137
            ->createServer()
138
            ->run();
139
    }
140
141
    protected function configurePubSubReplication()
142
    {
143
        if (config('websockets.replication.enabled') !== true) {
144
            return $this;
145
        }
146
147
        if (config('websockets.replication.driver') === 'redis') {
148
            $this->laravel->singleton(ReplicationInterface::class, function () {
149
                return (new RedisClient())->boot($this->loop);
150
            });
151
        }
152
153
        return $this;
154
    }
155
156
    protected function getDnsResolver(): ResolverInterface
157
    {
158
        if (! config('websockets.statistics.perform_dns_lookup')) {
159
            return new DnsResolver;
160
        }
161
162
        $dnsConfig = DnsConfig::loadSystemConfigBlocking();
163
164
        return (new DnsFactory)->createCached(
165
            $dnsConfig->nameservers
166
                ? reset($dnsConfig->nameservers)
167
                : '1.1.1.1',
168
            $this->loop
169
        );
170
    }
171
}
172