diff --git a/config/websockets.php b/config/websockets.php index 0a0f060..1ce1c77 100644 --- a/config/websockets.php +++ b/config/websockets.php @@ -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 ], /* diff --git a/src/Console/CleanStatistics.php b/src/Console/CleanStatistics.php new file mode 100644 index 0000000..23e3d1e --- /dev/null +++ b/src/Console/CleanStatistics.php @@ -0,0 +1,39 @@ +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!'); + } +} \ No newline at end of file diff --git a/src/WebSocketsServiceProvider.php b/src/WebSocketsServiceProvider.php index b859fde..bd895b7 100644 --- a/src/WebSocketsServiceProvider.php +++ b/src/WebSocketsServiceProvider.php @@ -40,6 +40,7 @@ class WebSocketsServiceProvider extends ServiceProvider $this->commands([ Console\StartWebSocketServer::class, + Console\CleanStatistics::class, ]); } diff --git a/tests/Commands/CleanStatisticsTest.php b/tests/Commands/CleanStatisticsTest.php new file mode 100644 index 0000000..9ac6d05 --- /dev/null +++ b/tests/Commands/CleanStatisticsTest.php @@ -0,0 +1,48 @@ +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()); + + + } +} \ No newline at end of file