Jake Vanderwerf
2026-02-14 27fb820ae9081fb56957cf75e79eccd8a99edd52
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
<?php
namespace JVBase\managers\queue;
if (!defined('ABSPATH')) {
    exit;
}
 
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;
 
class Queue
{
    private Storage $storage;
    private Processor $processor;
    private TypeRegistry $registry;
    public Executor $executor;
    private Locker $locker;
 
    public function __construct()
    {
        $this->storage = new Storage();
        $this->registry = new TypeRegistry();
        $this->locker = new Locker();
 
        $this->executor = new FilteredExecutor();
        $this->processor = new Processor($this->storage, $this->executor, $this->registry);
 
        add_action('jvb_process_queue', [$this, 'checkQueue']);
        add_action('jvb_queue_maintenance', [$this, 'maintenance']);
 
        if (!wp_next_scheduled('jvb_process_queue')) {
            wp_schedule_event(time(), 'every-minute', 'jvb_process_queue');
        }
        if (!wp_next_scheduled('jvb_queue_maintenance')) {
            wp_schedule_event(time(), 'hourly', 'jvb_queue_maintenance');
        }
 
        jvb_register_do_once('queue_admin_action_registered', [$this, 'registerAdminAction']);
        add_filter(BASE.'admin_action_filter', [$this, 'adminActionFilter'], 10, 3);
    }
 
    /**
     * Access type registry for registering operation configs
     */
    public function registry(): TypeRegistry
    {
        return $this->registry;
    }
 
    public function storage(): Storage
    {
        return $this->storage;
    }
 
    /**
     * Queue a new operation or merge into existing
     *
     * @param string $type Operation type
     * @param int $userId User ID
     * @param array $data Request data
     * @param array $options {
     *     @type string $priority     'low', 'normal', 'high'
     *     @type int $delay           Seconds to delay processing
     *     @type string $scheduled    Specific datetime to process
     *     @type array|string $depends_on  Operation IDs this depends on
     *     @type string|array $chunk_key   Key(s) to chunk (overrides registry)
     *     @type int $chunk_size      Chunk size (overrides registry)
     * }
     */
    public function add(string $type, int $userId, array $data, array $options = []): array|WP_Error
    {
        try {
            $incoming = $this->buildOperation($type, $userId, $data, $options);
 
            // Attempt pre-insert merge
            $merged = $this->tryMerge($incoming);
            if ($merged) {
                $this->runQueueOnShutdown();
                return $merged;
            }
 
            $this->storage->insert($incoming);
            $this->runQueueOnShutdown();
 
            return [
                'success'          => true,
                'operation_id'     => $incoming->id,
                'updated_existing' => false,
            ];
 
        } catch (\Exception $e) {
            JVB()->error()->log('queue', $e->getMessage(), $data, 'high');
            return new WP_Error('queue_failed', $e->getMessage());
        }
    }
 
    /**
     * Try to merge incoming operation into an existing pending/scheduled one.
     * Returns result array if merged, null if not.
     * @throws \Throwable
     */
    private function tryMerge(Operation $incoming): ?array
    {
        $mergeable = $this->registry->getMergeable($incoming->type);
        if (!$mergeable) {
            return null;
        }
 
        $existing = $this->storage->findMergeable($incoming->type, $incoming->userId);
        if (!$existing || !$mergeable->canMerge($existing, $incoming)) {
            return null;
        }
 
        $this->storage->withTransaction(function () use ($incoming, $existing, $mergeable) {
            $mergeable->merge($existing, $incoming);
 
            $this->storage->replaceDependency(
                $incoming->id,
                $existing->id
            );
 
            // Merge dependency arrays safely
            $existing->dependencies = array_values(array_unique(
                array_merge($existing->dependencies, $incoming->dependencies)
            ));
 
            // Prevent self dependency
            $existing->dependencies = array_diff(
                $existing->dependencies,
                [$existing->id]
            );
 
            $this->storage->save($existing);
 
            $incoming->state = 'completed';
            $incoming->outcome = 'merged';
            $incoming->merged_into = $existing->id;
            $this->storage->saveFinal($incoming);
        });
 
        return [
            'success'          => true,
            'operation_id'     => $existing->id,
            'updated_existing' => true,
        ];
    }
 
    /**
     * Alias for add() - backwards compatibility
     */
    public function queueOperation(string $type, int $userId, array $data, array $options = []): array|WP_Error
    {
        return $this->add($type, $userId, $data, $options);
    }
 
    public function checkQueue(): void
    {
        $this->locker->withLock(function () {
            $this->processor->run();
        });
 
    }
 
    public function maintenance(): void
    {
        $this->locker->withLock(function () {
            $this->storage->resetStuckOperations(30);
        });
        $this->runQueueOnShutdown();
    }
 
    // === Public Getters ===
 
    public function get(string $id): ?Operation
    {
        return $this->storage->find($id);
    }
 
    /**
     * Alias for get() - backwards compatibility
     */
    public function getOperation(string $id): ?Operation
    {
        return $this->get($id);
    }
 
    /**
     * Get a specific value from an operation - backwards compatibility
     */
    public function getOperationValue(string $id, string $column, bool $decodeJson = true): mixed
    {
        $op = $this->get($id);
        if (!$op) {
            return null;
        }
 
        return match($column) {
            'result'       => $op->result,
            'request_data' => $op->requestData,
            'state'        => $op->state,
            'outcome'      => $op->outcome,
            'type'         => $op->type,
            'user_id'      => $op->userId,
            'metadata'     => $op->metadata,
            'dependencies' => $op->dependencies,
            'merged_into'  => $op->merged_into,
            default        => null,
        };
    }
 
    public function getUserOperations(int $userId, array $filters = []): array
    {
        return $this->storage->getUserOperations($userId, $filters);
    }
 
    public function getStatus(): array
    {
        return $this->storage->getQueueStatus();
    }
 
    public function getUserStats(int $userId): array
    {
        return $this->storage->getUserStats($userId);
    }
 
    public function getInfo(): array
    {
        return $this->storage->getQueueInfo();
    }
 
    public function dismiss(string $id): bool
    {
        return $this->storage->dismiss($id);
    }
 
    /**
     * Cancel a pending/scheduled operation (deletes it)
     *
     * @param string $id Operation ID
     * @param int $userId User ID (for ownership verification)
     * @return bool True if cancelled
     */
    public function cancel(string $id, int $userId): bool
    {
        $op = $this->get($id);
        if (!$op || $op->userId !== $userId) {
            return false;
        }
 
        // Can only cancel pending or scheduled operations
        if (!in_array($op->state, ['pending', 'scheduled'])) {
            return false;
        }
 
        return $this->storage->delete($id);
    }
 
    /**
     * Retry a failed operation
     *
     * @param string $id Operation ID
     * @param int $userId User ID (for ownership verification)
     * @return bool True if reset for retry
     */
    public function retry(string $id, int $userId): bool
    {
 
        $op = $this->get($id);
        if (!$op || $op->userId !== $userId) {
            return false;
        }
 
        // Can only retry completed operations with failed outcomes
        if ($op->state !== 'completed' || !in_array($op->outcome, ['failed', 'failed_permanent'])) {
            return false;
        }
 
        $op->state = 'pending';
        $op->outcome = 'pending';
        $op->errorMessage = null;
        $op->lastErrorHash = null;
        $op->scheduledAt = current_time('mysql');
        $op->retries++;
        error_log('[Queue]Retrying operation '.print_r($op->id, true));
        $saved = $this->storage->save($op);
 
        if ($saved) {
            $this->runQueueOnShutdown();
        }
 
        return $saved;
    }
 
    /**
     * Update an operation's data or metadata
     *
     * @param string $id Operation ID
     * @param array $updates Fields to update (requestData, metadata, etc.)
     * @param int|null $userId Optional user ID for ownership verification
     * @return bool True if updated
     */
    public function update(string $id, array $updates, ?int $userId = null): bool
    {
        $op = $this->get($id);
        if (!$op) {
            return false;
        }
 
        if ($userId !== null && $op->userId !== $userId) {
            return false;
        }
 
        // Apply allowed updates
        foreach ($updates as $field => $value) {
            match($field) {
                'requestData' => $op->requestData = $value,
                'metadata'    => $op->metadata = array_merge($op->metadata, $value),
                'priority'    => $op->priority = $value,
                'state'       => $op->state = $value,
                'outcome'     => $op->outcome = $value,
                'result'      => $op->result = $value,
                default       => null,
            };
        }
        error_log('[Queue]: updating operation '.print_r($op->id, true));
        return $this->storage->saveProgress($op);
    }
    // === Private Helpers ===
 
    private function buildOperation(string $type, int $userId, array $data, array $options): Operation
    {
        $op = new Operation();
 
        // Use provided operation_id or generate one
        $op->id = !empty($options['operation_id'])
            ? $options['operation_id']
            : 'u' . $userId . '_' . uniqid('op_');
 
        $op->type = $type;
        $op->userId = $userId;
        $op->requestData = $data;
        $op->priority = $options['priority'] ?? 'normal';
        $op->state = !empty($options['delay']) || !empty($options['scheduled']) ? 'scheduled' : 'pending';
        $op->scheduledAt = $this->calculateScheduledTime($options);
 
        // Chunk config: explicit options override registry
        $chunkConfig = null;
        if (!empty($options['chunk_key'])) {
            $chunkConfig = [
                'key'  => $options['chunk_key'],
                'size' => $options['chunk_size'] ?? 10,
            ];
        } else {
            $chunkConfig = $this->registry->getChunkConfig($type);
        }
 
        if ($chunkConfig) {
            $op->metadata['chunk_key'] = $chunkConfig['key'];
            $op->metadata['chunk_size'] = $chunkConfig['size'];
            $op->totalItems = $this->countItems($data, $chunkConfig['key']);
        }
 
        // Dependencies
        if (!empty($options['depends_on'])) {
            $op->dependencies = is_string($options['depends_on'])
                ? explode(',', $options['depends_on'])
                : $options['depends_on'];
        }
 
        return $op;
    }
 
    private function countItems(array $data, string|array $keys): int
    {
        $keys = (array) $keys;
        $total = 0;
        foreach ($keys as $key) {
            if (isset($data[$key]) && is_array($data[$key])) {
                $total += count($data[$key]);
            }
        }
        return max(1, $total);
    }
 
    private function calculateScheduledTime(array $options): string
    {
        if (!empty($options['delay'])) {
            return date('Y-m-d H:i:s', current_time('timestamp') + (int)$options['delay']);
        }
        if (!empty($options['scheduled'])) {
            return $options['scheduled'];
        }
        return current_time('mysql');
    }
 
    private function runQueueOnShutdown(): void
    {
        if (!has_action('shutdown', [$this, 'processQueueOnShutdown'])) {
            add_action('shutdown', [$this, 'processQueueOnShutdown'], 100);
        }
    }
 
    public function processQueueOnShutdown(): void
    {
        remove_action('shutdown', [$this, 'processQueueOnShutdown']);
 
        if (function_exists('fastcgi_finish_request')) {
            fastcgi_finish_request();
        }
 
        $this->checkQueue();
    }
 
    public function registerAdminAction():void
    {
        $admin = JVB()->admin();
        $admin->registerAction(
            'Restart Stuck Operations',
            'restart-stuck-operations',
            'manage_options',
            'arrows-clockwise'
        );
        $admin->registerAction(
            'Unlock Queue',
            'unlock-operation-queue',
            'manage_options',
            'infinity'
        );
    }
    /**
     * @param WP_REST_Response $response
     * @param string $action
     *
     * @return bool|WP_REST_Response
     */
    public function adminActionFilter(WP_REST_Response $response, WP_REST_Request $request, string $action):WP_REST_Response|bool
    {
        switch ($action) {
            case 'unlock-operation-queue':
                error_log('Unlocking Queue');
                $this->locker->unlock();
                return new WP_REST_Response([
                    'success'   => true,
                    'message'   => 'Unlocked Queue'
                ]);
            case 'restart-stuck-operations':
                error_log('Restarting stuck operations');
                $this->maintenance();
                return new WP_REST_Response([
                    'success'   => true,
                    'message'   => 'Restarted Stuck Operations'
                ]);
            default:
                return $response;
        }
    }
}