1<?php
2
3// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
4// See the LICENCE file in the repository root for full licence text.
5
6namespace App\Console\Commands;
7
8use App\Models\Notification;
9use App\Models\UserNotification;
10use Illuminate\Console\Command;
11
12class NotificationsCleanup extends Command
13{
14 const MAX_PER_LOOP = 1000;
15 const NOTIFICATION_ID_BUFFER = 1000;
16
17 protected $signature = 'notifications:cleanup';
18
19 protected $description = 'Deletes old notifications';
20
21 public function handle()
22 {
23 $total = $GLOBALS['cfg']['osu']['notification']['cleanup']['max_delete_per_run'];
24
25 if ($total === 0) {
26 return;
27 }
28
29 $perLoop = min($total, static::MAX_PER_LOOP);
30 $loops = $total / $perLoop;
31
32 $maxNotificationId = optional(UserNotification::orderBy('id', 'ASC')->first())->notification_id;
33
34 if ($maxNotificationId === null || $maxNotificationId < static::NOTIFICATION_ID_BUFFER) {
35 $this->line('No notifications to delete');
36
37 return;
38 }
39
40 $maxNotificationId -= static::NOTIFICATION_ID_BUFFER;
41
42 $this->line("Deleting notifications up to {$maxNotificationId}");
43
44 $deletedTotal = 0;
45
46 for ($i = 0; $i < $loops; $i++) {
47 $deleted = Notification::where('id', '<', $maxNotificationId)->limit($perLoop)->delete();
48 datadog_increment('notifications_cleanup.notifications', value: $deleted);
49
50 $deletedTotal += $deleted;
51 }
52
53 $this->line("Deleted {$deletedTotal} notifications.");
54 }
55}