Skip to content
This repository has been archived by the owner on Feb 7, 2024. It is now read-only.

Commit

Permalink
Merge branch 'master' of github.com:beyondcode/laravel-websockets
Browse files Browse the repository at this point in the history
  • Loading branch information
mpociot committed Dec 4, 2018
2 parents 1f0a153 + e738d30 commit dd283c6
Show file tree
Hide file tree
Showing 7 changed files with 79 additions and 58 deletions.
17 changes: 13 additions & 4 deletions config/websockets.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,19 @@
*/
'max_request_size_in_kb' => 250,

/*
* This model will be used to store the statistics of the WebSocketsServer
*/
'statistics_model' => \BeyondCode\LaravelWebSockets\Statistics\Models\WebSocketsStatisticsEntry::class,
'statistics' => [
/*
* This model will be used to store the statistics of the WebSocketsServer.
* The only requirement is that the model should be or extend
* `WebSocketsStatisticsEntry` provided by this package.
*/
'model' => \BeyondCode\LaravelWebSockets\Statistics\Models\WebSocketsStatisticsEntry::class,

/*
* Here you can specify the interval in seconds at which statistics should be logged.
*/
'interval_in_seconds' => 60,
],

/*
* Define the optional SSL context for your WebSocket connections.
Expand Down
3 changes: 1 addition & 2 deletions src/Console/StartWebSocketServer.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,11 @@ protected function configureStatisticsLogger()

$browser = new Browser($this->loop, $connector);


app()->singleton(StatisticsLoggerInterface::class, function() use ($browser) {
return new HttpStatisticsLogger(app(ChannelManager::class), $browser);
});

$this->loop->addPeriodicTimer(5, function() {
$this->loop->addPeriodicTimer(config('websockets.statistics.interval_in_seconds'), function() {
StatisticsLogger::save();
});

Expand Down
22 changes: 13 additions & 9 deletions src/Statistics/Events/StatisticsUpdated.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace BeyondCode\LaravelWebsockets\Statistics\Events;

use BeyondCode\LaravelWebSockets\Dashboard\DashboardLogger;
use BeyondCode\LaravelWebSockets\Statistics\Models\WebSocketsStatisticsEntry;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Queue\SerializesModels;
Expand All @@ -11,27 +12,30 @@ class StatisticsUpdated implements ShouldBroadcast
{
use SerializesModels;

public $statisticModel;
/** @var \BeyondCode\LaravelWebSockets\Statistics\Models\WebSocketsStatisticsEntry */
protected $webSocketsStatisticsEntry;

public function __construct($statisticModel)
public function __construct(WebSocketsStatisticsEntry $webSocketsStatisticsEntry)
{
$this->statisticModel = $statisticModel;
$this->webSocketsStatisticsEntry = $webSocketsStatisticsEntry;
}

public function broadcastWith()
{
return [
'time' => (string)$this->statisticModel->created_at,
'app_id' => $this->statisticModel->app_id,
'peak_connection_count' => $this->statisticModel->peak_connection_count,
'websocket_message_count' => $this->statisticModel->websocket_message_count,
'api_message_count' => $this->statisticModel->api_message_count,
'time' => $this->webSocketsStatisticsEntry->created_at->timestamp,
'app_id' => $this->webSocketsStatisticsEntry->appId,
'peak_connection_count' => $this->webSocketsStatisticsEntry->peakConnectionCount,
'websocket_message_count' => $this->webSocketsStatisticsEntry->webSocketMessageCount,
'api_message_count' => $this->webSocketsStatisticsEntry->apiMessageCount,
];
}

public function broadcastOn()
{
return new PrivateChannel(str_after(DashboardLogger::LOG_CHANNEL_PREFIX . 'statistics', 'private-'));
$channelName = str_after(DashboardLogger::LOG_CHANNEL_PREFIX . 'statistics', 'private-');

return new PrivateChannel($channelName);
}

public function broadcastAs()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public function store(Request $request)
'api_message_count' => 'required|integer',
]);

$webSocketsStatisticsEntryModelClass = config('websockets.statistics_model');
$webSocketsStatisticsEntryModelClass = config('websockets.statistics.model');

$statisticModel = $webSocketsStatisticsEntryModelClass::create($validatedAttributes);

Expand Down
46 changes: 22 additions & 24 deletions src/Statistics/Logger/HttpStatisticsLogger.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@

class HttpStatisticsLogger implements StatisticsLogger
{
/** @var Statistic[] */
/** @var \BeyondCode\LaravelWebSockets\Statistics\Statistic[] */
protected $statistics = [];

/** @var \BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager */
protected $channelManager;

/** @var Browser */
/** @var \Clue\React\Buzz\Browser */
protected $browser;

public function __construct(ChannelManager $channelManager, Browser $browser)
Expand All @@ -29,37 +29,39 @@ public function __construct(ChannelManager $channelManager, Browser $browser)

public function webSocketMessage(ConnectionInterface $connection)
{
$this->initializeStatistics($connection->app->id);

$this->statistics[$connection->app->id]->webSocketMessage();
$this
->findOrMakeStatisticForAppId($connection->app->id)
->webSocketMessage();
}

public function apiMessage($appId)
{
$this->initializeStatistics($appId);

$this->statistics[$appId]->apiMessage();
$this
->findOrMakeStatisticForAppId($appId)
->apiMessage();
}

public function connection(ConnectionInterface $connection)
{
$this->initializeStatistics($connection->app->id);

$this->statistics[$connection->app->id]->connection();
$this
->findOrMakeStatisticForAppId($connection->app->id)
->connection();
}

public function disconnection(ConnectionInterface $connection)
{
$this->initializeStatistics($connection->app->id);

$this->statistics[$connection->app->id]->disconnection();
$this
->findOrMakeStatisticForAppId($connection->app->id)
->disconnection();
}

protected function initializeStatistics($id)
protected function findOrMakeStatisticForAppId($appId): Statistic
{
if (!isset($this->statistics[$id])) {
$this->statistics[$id] = new Statistic($id);
if (!isset($this->statistics[$appId])) {
$this->statistics[$appId] = new Statistic($appId);
}

return $this->statistics[$appId];
}

public function save()
Expand All @@ -70,19 +72,15 @@ public function save()
continue;
}

$this->browser
$this
->browser
->post(
action([WebSocketStatisticsEntriesController::class, 'store']),
['Content-Type' => 'application/json'],
stream_for(json_encode($statistic->toArray()))
);

// Reset connection and message count
$currentConnectionCount = collect($this->channelManager->getChannels($appId))
->sum(function ($channel) {
return count($channel->getSubscribedConnections());
});

$currentConnectionCount = $this->channelManager->getConnectionCount($appId);
$statistic->reset($currentConnectionCount);
}
}
Expand Down
6 changes: 6 additions & 0 deletions src/WebSockets/Channels/ChannelManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,12 @@ public function getChannels(string $appId): array
return $this->channels[$appId] ?? [];
}

public function getConnectionCount(string $appId): int
{
return collect($this->getChannels($appId))
->sum->getSubscribedConnections();
}

public function removeFromAllChannels(ConnectionInterface $connection)
{
if (!isset($connection->app)) {
Expand Down
41 changes: 23 additions & 18 deletions src/WebSocketsServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,22 +22,21 @@ class WebSocketsServiceProvider extends ServiceProvider
public function boot()
{
$this->publishes([
__DIR__.'/../config/websockets.php' => base_path('config/websockets.php'),
__DIR__ . '/../config/websockets.php' => base_path('config/websockets.php'),
], 'config');

if (! class_exists('CreateWebSocketsStatisticsEntries')) {
if (!class_exists('CreateWebSocketsStatisticsEntries')) {
$this->publishes([
__DIR__.'/../database/migrations/create_websockets_statistics_entries_table.php.stub' => database_path('migrations/'.date('Y_m_d_His', time()).'_create_websockets_statistics_entries_table.php'),
__DIR__ . '/../database/migrations/create_websockets_statistics_entries_table.php.stub' => database_path('migrations/' . date('Y_m_d_His', time()) . '_create_websockets_statistics_entries_table.php'),
], 'migrations');
}

$this->registerRouteMacro();
$this
->registerRouteMacro()
->registerStatisticRoute()
->registerDashboardGate();

$this->registerStatisticRoute();

$this->registerDashboardGate();

$this->loadViewsFrom(__DIR__.'/../resources/views/', 'websockets');
$this->loadViewsFrom(__DIR__ . '/../resources/views/', 'websockets');

$this->commands([
Console\StartWebSocketServer::class,
Expand All @@ -46,44 +45,50 @@ public function boot()

public function register()
{
$this->mergeConfigFrom(__DIR__.'/../config/websockets.php', 'websockets');
$this->mergeConfigFrom(__DIR__ . '/../config/websockets.php', 'websockets');

$this->app->singleton('websockets.router', function() {
$this->app->singleton('websockets.router', function () {
return new Router();
});

$this->app->singleton(ChannelManager::class, function() {
$this->app->singleton(ChannelManager::class, function () {
return new ChannelManager();
});

$this->app->singleton(AppProvider::class, function() {
$this->app->singleton(AppProvider::class, function () {
return app(config('websockets.app_provider'));
});
}

protected function registerRouteMacro()
{
Route::macro('webSockets', function($prefix = 'laravel-websockets') {
Route::prefix($prefix)->namespace('\\')->middleware(Authorize::class)->group(function() {
Route::get('/', ShowDashboard::class);
Route::get('/api/{appId}/statistics', DashboardApiController::class.'@getStatistics');
Route::macro('webSockets', function ($prefix = 'laravel-websockets') {
Route::prefix($prefix)->namespace('\\')->middleware(Authorize::class)->group(function () {
Route::get('/', ShowDashboard::class);
Route::get('/api/{appId}/statistics', DashboardApiController::class . '@getStatistics');
Route::post('auth', AuthenticateDashboard::class);
Route::post('event', SendMessage::class);
});
});

return $this;
}

protected function registerStatisticRoute()
{
Route::prefix('/laravel-websockets')->namespace('\\')->group(function() {
Route::prefix('/laravel-websockets')->namespace('\\')->group(function () {
Route::post('statistics', [WebSocketStatisticsEntriesController::class, 'store']);
});

return $this;
}

protected function registerDashboardGate()
{
Gate::define('viewWebSocketsDashboard', function ($user = null) {
return app()->environment('local');
});

return $this;
}
}

0 comments on commit dd283c6

Please sign in to comment.