Jake Vanderwerf
2026-05-11 ac444cba221832c012c0435fdc8339fe9f37febb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
<?php
namespace JVBase\managers\queue;
if (!defined('ABSPATH')) {
    exit;
}
 
final class Metrics
{
    public function __construct(
        private \wpdb $db,
        private string $queueTable,
        private string $statsTable
    ) {}
 
    private function sinceDate(int $hours): string
    {
        return gmdate('Y-m-d H:i:s', time() - ($hours * HOUR_IN_SECONDS));
    }
 
    /* ---------- Live metrics (raw queue table) ---------- */
 
    public function liveSummary(int $hours = 24): array
    {
        $since = $this->sinceDate($hours);
 
        $sql = "
        SELECT
            COUNT(*) AS total,
            SUM(outcome = 'success') AS success,
            SUM(outcome = 'partial') AS partial,
            SUM(outcome IN ('failed', 'failed_permanent')) AS failed,
            SUM(state IN ('pending','scheduled','processing')) AS active
        FROM {$this->queueTable}
        WHERE created_at >= %s
    ";
 
        return (array) $this->db->get_row(
            $this->db->prepare($sql, $since),
            ARRAY_A
        );
    }
 
 
    public function byHour(int $hours = 24): array
    {
        $since = $this->sinceDate($hours);
 
        $sql = "
        SELECT
            HOUR(created_at) AS hour,
            COUNT(*) AS total,
            SUM(outcome = 'success') AS success,
            SUM(outcome IN ('failed','failed_permanent')) AS failed
        FROM {$this->queueTable}
        WHERE created_at >= %s
        GROUP BY hour
        ORDER BY hour ASC
    ";
 
        $rows = $this->db->get_results(
            $this->db->prepare($sql, $since),
            ARRAY_A
        );
 
        $result = [];
        foreach ($rows as $row) {
            $key = str_pad($row['hour'], 2, '0', STR_PAD_LEFT);
            $result[$key] = [
                'total'   => (int) $row['total'],
                'success' => (int) $row['success'],
                'failed'  => (int) $row['failed'],
            ];
        }
 
        return $result;
    }
 
 
    public function liveByUser(int $hours = 24, int $limit = 100): array
    {
        $since = $this->sinceDate($hours);
 
        $sql = "
        SELECT
            user_id,
            COUNT(*) AS total,
            SUM(outcome = 'success') AS success,
            SUM(outcome IN ('failed','failed_permanent')) AS failed,
            AVG(retries) AS avg_retries
        FROM {$this->queueTable}
        WHERE created_at >= %s
        GROUP BY user_id
        ORDER BY total DESC
        LIMIT %d
    ";
 
        return $this->db->get_results(
            $this->db->prepare($sql, $since, $limit),
            ARRAY_A
        );
    }
 
    public function liveQueueHealth(): array
    {
        $sql = "
        SELECT
            SUM(state = 'pending') AS pending,
            SUM(state = 'scheduled') AS scheduled,
            SUM(state = 'processing') AS processing,
            MIN(scheduled_at) AS oldest_scheduled,
            SUM(
                state = 'processing'
                AND started_at < DATE_SUB(NOW(), INTERVAL 15 MINUTE)
            ) AS stuck
        FROM {$this->queueTable}
    ";
 
        return (array) $this->db->get_row($sql, ARRAY_A);
    }
 
 
    public function liveByType(int $hours = 24): array
    {
        $since = gmdate('Y-m-d H:i:s', time() - $hours * HOUR_IN_SECONDS);
 
        $sql = "
        SELECT
            type,
            COUNT(*) AS total,
            SUM(outcome = 'success') AS success,
            SUM(outcome = 'partial') AS partial,
            SUM(outcome IN ('failed','failed_permanent')) AS failed,
            AVG(TIMESTAMPDIFF(SECOND, started_at, completed_at)) AS avg_duration
        FROM {$this->queueTable}
        WHERE completed_at IS NOT NULL
          AND created_at >= %s
        GROUP BY type
    ";
 
        return $this->db->get_results(
            $this->db->prepare($sql, $since),
            ARRAY_A
        );
    }
 
 
    /* ---------- Historical metrics (stats table) ---------- */
 
    public function dailySummary(
        \DateTimeInterface $from,
        \DateTimeInterface $to
    ): array {
        $sql = "
        SELECT
            date,
            SUM(total_operations) AS total,
            SUM(successful_operations) AS success,
            SUM(partial_operations) AS partial,
            SUM(failed_operations) AS failed,
            SUM(failed_permanent_operations) AS failed_permanent,
            SUM(total_items_processed) AS items,
            AVG(average_duration) AS avg_duration,
            MAX(max_duration) AS max_duration
        FROM {$this->statsTable}
        WHERE date BETWEEN %s AND %s
        GROUP BY date
        ORDER BY date
    ";
 
        return $this->db->get_results(
            $this->db->prepare(
                $sql,
                $from->format('Y-m-d'),
                $to->format('Y-m-d')
            ),
            ARRAY_A
        );
    }
 
 
    public function dailyByType(
        \DateTimeInterface $from,
        \DateTimeInterface $to
    ): array {
        $sql = "
        SELECT
            date,
            type,
            total_operations,
            successful_operations,
            partial_operations,
            failed_operations,
            failed_permanent_operations,
            average_duration,
            max_duration
        FROM {$this->statsTable}
        WHERE date BETWEEN %s AND %s
        ORDER BY date, type
    ";
 
        return $this->db->get_results(
            $this->db->prepare(
                $sql,
                $from->format('Y-m-d'),
                $to->format('Y-m-d')
            ),
            ARRAY_A
        );
    }
}