prefix . 'tgp360_queue'; } /** * Creates or updates the table (dbDelta). */ public static function install() { global $wpdb; require_once ABSPATH . 'wp-admin/includes/upgrade.php'; $table = self::table(); $charset = $wpdb->get_charset_collate(); dbDelta( "CREATE TABLE {$table} ( id bigint(20) unsigned NOT NULL AUTO_INCREMENT, idempotency_key varchar(64) NOT NULL, source varchar(20) NOT NULL DEFAULT '', form_ref varchar(64) NOT NULL DEFAULT '', payload longtext NOT NULL, attempts smallint(5) unsigned NOT NULL DEFAULT 0, last_error varchar(64) NOT NULL DEFAULT '', next_attempt_at datetime NOT NULL, created_at datetime NOT NULL, PRIMARY KEY (id), UNIQUE KEY idempotency_key (idempotency_key), KEY next_attempt_at (next_attempt_at) ) {$charset};" ); update_option( TGP360_Settings::DB_VERSION_OPTION, self::DB_VERSION ); } /** * Seconds to wait after a failed attempt, or null when no attempt is left. Pure. * * @param int $attempts Attempts made so far (1 = the first, immediate one). * @return int|null */ public static function next_delay( $attempts ) { $attempts = (int) $attempts; if ( $attempts < 1 || $attempts >= self::MAX_ATTEMPTS ) { return null; } return self::DELAYS[ $attempts - 1 ]; } /** * Queues a submission after its first attempt failed. * * @param array $job Job (payload, idempotency_key, source, form). * @param int $attempts Attempts made. * @param string $last_error Last error code. * @return bool False when the queue is full or the row could not be stored. */ public static function add( array $job, $attempts, $last_error ) { global $wpdb; if ( self::count() >= self::MAX_ROWS ) { return false; } $delay = self::next_delay( $attempts ); $now = time(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- the plugin's own table; nothing to cache. $stored = $wpdb->insert( self::table(), array( 'idempotency_key' => $job['idempotency_key'], 'source' => substr( (string) $job['source'], 0, 20 ), 'form_ref' => substr( (string) $job['form'], 0, 64 ), 'payload' => wp_json_encode( $job['payload'] ), 'attempts' => (int) $attempts, 'last_error' => substr( (string) $last_error, 0, 64 ), 'next_attempt_at' => gmdate( 'Y-m-d H:i:s', $now + ( null === $delay ? 300 : $delay ) ), 'created_at' => gmdate( 'Y-m-d H:i:s', $now ), ), array( '%s', '%s', '%s', '%s', '%d', '%s', '%s', '%s' ) ); self::ensure_scheduled(); return false !== $stored; } /** * Rows waiting. * * @return int */ public static function count() { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- the plugin's own table; the count must be live. return (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}tgp360_queue" ); } /** * Deletes every queued submission (the admin's "Delete queued submissions" action). * * @return int Rows deleted. */ public static function delete_all() { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- the plugin's own table. return (int) $wpdb->query( "DELETE FROM {$wpdb->prefix}tgp360_queue" ); } /** * Removes one row. * * @param int $id Row id. */ private static function remove( $id ) { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- the plugin's own table. $wpdb->delete( self::table(), array( 'id' => (int) $id ), array( '%d' ) ); } /** * Sends what is due (WP-Cron, every 5 minutes; also the admin's "Retry now"). Stops early when TGP 360 rate * limits or refuses the key, so a problem never turns into a burst of requests. * * @param bool $all_now Treat every row as due (the admin's "Retry now"). * @return array{sent:int,rescheduled:int,dropped:int} */ public static function process( $all_now = false ) { global $wpdb; $totals = array( 'sent' => 0, 'rescheduled' => 0, 'dropped' => 0, ); self::purge_expired(); $now = time(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- the plugin's own table; rows must be live. $rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}tgp360_queue WHERE next_attempt_at <= %s ORDER BY next_attempt_at ASC, id ASC LIMIT %d", gmdate( 'Y-m-d H:i:s', $all_now ? $now + 10 * YEAR_IN_SECONDS : $now ), self::BATCH ), ARRAY_A ); foreach ( (array) $rows as $row ) { // Claim the row (compare-and-set) so two overlapping cron runs never send it at the same moment. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- the plugin's own table. $claimed = $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->prefix}tgp360_queue SET next_attempt_at = %s WHERE id = %d AND next_attempt_at = %s", gmdate( 'Y-m-d H:i:s', $now + self::LEASE ), (int) $row['id'], $row['next_attempt_at'] ) ); if ( 1 !== (int) $claimed ) { continue; } $payload = json_decode( (string) $row['payload'], true ); $attempts = (int) $row['attempts'] + 1; $job = array( 'payload' => is_array( $payload ) ? $payload : array(), 'idempotency_key' => (string) $row['idempotency_key'], 'source' => (string) $row['source'], 'form' => (string) $row['form_ref'], ); $outcome = TGP360_Delivery::attempt( $job ); $kind = $outcome['kind']; if ( 'delivered' === $kind || 'reject' === $kind ) { self::remove( $row['id'] ); TGP360_Delivery::record( $job, $outcome, $attempts ); if ( 'delivered' === $kind ) { ++$totals['sent']; } else { ++$totals['dropped']; } continue; } $delay = self::next_delay( $attempts ); if ( null === $delay ) { self::remove( $row['id'] ); $outcome['result'] = 'expired'; TGP360_Delivery::record( $job, $outcome, $attempts ); ++$totals['dropped']; } else { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- the plugin's own table. $wpdb->update( self::table(), array( 'attempts' => $attempts, 'last_error' => substr( (string) $outcome['code'], 0, 64 ), 'next_attempt_at' => gmdate( 'Y-m-d H:i:s', time() + $delay ), ), array( 'id' => (int) $row['id'] ), array( '%d', '%s', '%s' ), array( '%d' ) ); $outcome['result'] = 'retrying'; TGP360_Delivery::record( $job, $outcome, $attempts ); ++$totals['rescheduled']; } // Rate limited, key refused or TGP 360 down: leave the rest for the next run. if ( in_array( $kind, array( 'retry', 'config', 'not_configured' ), true ) ) { break; } } return $totals; } /** * Removes rows older than MAX_AGE (only possible when WP-Cron stopped for a long time) — never kept forever. */ private static function purge_expired() { global $wpdb; $cutoff = gmdate( 'Y-m-d H:i:s', time() - self::MAX_AGE ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- the plugin's own table. $old = $wpdb->get_results( $wpdb->prepare( "SELECT id, source, form_ref, attempts, last_error FROM {$wpdb->prefix}tgp360_queue WHERE created_at < %s LIMIT 100", $cutoff ), ARRAY_A ); foreach ( (array) $old as $row ) { self::remove( $row['id'] ); TGP360_Delivery::log( array( 'src' => $row['source'], 'form' => $row['form_ref'], 'result' => 'expired', 'code' => $row['last_error'], 'try' => (int) $row['attempts'], ) ); } } /** * Adds the 5-minute schedule. * * @param array $schedules Schedules. * @return array */ public static function cron_schedules( $schedules ) { $schedules[ self::SCHEDULE ] = array( 'interval' => 300, 'display' => __( 'Every 5 minutes (TGP 360 retry queue)', 'tgp-360' ), ); return $schedules; } /** * Schedules the worker if it is not scheduled. */ public static function ensure_scheduled() { if ( ! wp_next_scheduled( self::CRON_HOOK ) ) { wp_schedule_event( time() + 300, self::SCHEDULE, self::CRON_HOOK ); } } /** * Unschedules the worker (deactivation). */ public static function unschedule() { wp_clear_scheduled_hook( self::CRON_HOOK ); } }