This commit is contained in:
Marcel Pociot 2018-12-04 11:48:07 +01:00
parent c050fe87e2
commit f89278ede1
4 changed files with 94 additions and 0 deletions

View File

@ -54,6 +54,12 @@ return [
* Here you can specify the interval in seconds at which statistics should be logged.
*/
'interval_in_seconds' => 60,
/*
* When the clean-command is executed, all recorded statistics older than
* the number of days specified here will be deleted.
*/
'delete_statistics_older_than_days' => 60
],
/*

View File

@ -0,0 +1,39 @@
<?php
namespace BeyondCode\LaravelWebSockets\Console;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Builder;
class CleanStatistics extends Command
{
protected $signature = 'websockets:clean
{appId? : (optional) The app id that will be cleaned.}';
protected $description = 'Clean up old statistics from the websocket log.';
public function handle()
{
$this->comment('Cleaning WebSocket Statistics...');
$appId = $this->argument('appId');
$maxAgeInDays = config('websockets.statistics.delete_statistics_older_than_days');
$cutOffDate = Carbon::now()->subDay($maxAgeInDays)->format('Y-m-d H:i:s');
$webSocketsStatisticsEntryModelClass = config('websockets.statistics.model');
$amountDeleted = $webSocketsStatisticsEntryModelClass::where('created_at', '<', $cutOffDate)
->when(! is_null($appId), function (Builder $query) use ($appId) {
$query->where('app_id', $appId);
})
->delete();
$this->info("Deleted {$amountDeleted} record(s) from the WebSocket statistics.");
$this->comment('All done!');
}
}

View File

@ -40,6 +40,7 @@ class WebSocketsServiceProvider extends ServiceProvider
$this->commands([
Console\StartWebSocketServer::class,
Console\CleanStatistics::class,
]);
}

View File

@ -0,0 +1,48 @@
<?php
namespace BeyondCode\LaravelWebSockets\Tests\Commands;
use Artisan;
use BeyondCode\LaravelWebSockets\Statistics\Models\WebSocketsStatisticsEntry;
use Carbon\Carbon;
use BeyondCode\LaravelWebSockets\Tests\TestCase;
class CleanStatisticsTest extends TestCase
{
public function setUp()
{
parent::setUp();
Carbon::setTestNow(Carbon::create(2018, 1, 1, 00, 00, 00));
$this->app['config']->set('websockets.statistics.delete_statistics_older_than_days', 31);
}
/** @test */
public function it_can_clean_the_statistics()
{
collect(range(1, 60))->each(function (int $index) {
WebSocketsStatisticsEntry::create([
'app_id' => 'app_id',
'peak_connection_count' => 1,
'websocket_message_count' => 2,
'api_message_count' => 3,
'created_at' => Carbon::now()->subDays($index)->startOfDay(),
]);
});
$this->assertCount(60, WebSocketsStatisticsEntry::all());
Artisan::call('websockets:clean');
$this->assertCount(31, WebSocketsStatisticsEntry::all());
$cutOffDate = Carbon::now()->subDays(31)->format('Y-m-d H:i:s');
$this->assertCount(0, WebSocketsStatisticsEntry::where('created_at', '<', $cutOffDate)->get());
}
}