Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
CRAP
0.00% covered (danger)
0.00%
0 / 1
PurgeApiConsumerEndpoints
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
42
0.00% covered (danger)
0.00%
0 / 1
 handle
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
42
1<?php
2
3namespace App\Console\Commands;
4
5use Illuminate\Console\Command;
6use Illuminate\Support\Facades\DB;
7use Illuminate\Support\Facades\Log;
8
9/**
10 * Daily retention janitor for `tbl_api_consumer_endpoints`.
11 *
12 * AuthenticateWithToken writes one row per external-consumer request,
13 * including the (capped) response body, so the table grows fast. This keeps
14 * only the last N days (default 3).
15 *
16 * Deletes in batches of `--batch` rows ordered by id, sleeping `--sleep` ms
17 * between batches, so each DELETE holds its locks briefly and the middleware's
18 * concurrent INSERTs are never blocked for long. The cutoff is computed once
19 * up front so rows that age past it mid-run aren't chased.
20 */
21class PurgeApiConsumerEndpoints extends Command
22{
23    protected $signature = 'api-consumer-endpoints:purge
24        {--days=3 : Keep rows newer than this many days}
25        {--batch=10000 : Rows deleted per DELETE statement}
26        {--sleep=200 : Milliseconds to pause between batches}';
27
28    protected $description = 'Purge tbl_api_consumer_endpoints rows older than --days (default 3) in batches';
29
30    public function handle(): int
31    {
32        $days = (int) $this->option('days');
33        $batch = (int) $this->option('batch');
34        $sleepMs = (int) $this->option('sleep');
35
36        if ($days < 1 || $batch < 1 || $sleepMs < 0) {
37            $this->error('--days and --batch must be >= 1, --sleep must be >= 0.');
38
39            return Command::INVALID;
40        }
41
42        $cutoff = now()->subDays($days);
43        $total = 0;
44
45        do {
46            $deleted = DB::table('tbl_api_consumer_endpoints')
47                ->where('created_at', '<', $cutoff)
48                ->orderBy('id')
49                ->limit($batch)
50                ->delete();
51
52            $total += $deleted;
53
54            if ($deleted > 0 && $sleepMs > 0) {
55                usleep($sleepMs * 1000);
56            }
57        } while ($deleted === $batch);
58
59        $message = "api-consumer-endpoints:purge — deleted {$total} rows older than {$cutoff->toDateTimeString()}.";
60        $this->info($message);
61        Log::info($message);
62
63        return Command::SUCCESS;
64    }
65}