0, 'sent' => 0, 'failed' => 0, 'pending' => 0, 'rate_per_min' => 0.0, 'eta' => null, 'stalled' => false, ); $batches = self::batches( $campaign_id ); if ( empty( $batches ) ) { return $empty; } $out = $empty; $live = null; foreach ( $batches as $batch ) { $counts = Mailpuff_Outbox::progress( (int) $batch->id ); $out['total'] += $counts['total']; $out['sent'] += $counts['sent']; $out['failed'] += $counts['failed']; $out['pending'] += $counts['pending'] + $counts['sending']; if ( self::is_live( $batch ) && ( $counts['pending'] + $counts['sending'] ) > 0 ) { $live = $batch; // The latest live batch wins (rows come oldest first). } } $now = Mailpuff_Send_Cap::local_seconds( current_time( 'mysql' ) ); $recent = self::recent_sends( $campaign_id, $now ); $window = Mailpuff_Send_Cap::window(); $out['rate_per_min'] = self::rate( $recent, $now, $live, $window ); if ( null === $live ) { return $out; } // The daily cap: the plan's on PostShiba, or the warm-up's while it lasts. $day = Mailpuff_Send_Cap::day_window(); $out['eta'] = self::eta( $out['pending'], $out['rate_per_min'], $window, $day, $now ); $out['stalled'] = self::batch_stalled( $live, $campaign_id, $now, $window, $day ); return $out; } /** * Campaigns that are sending and have stopped moving. * * @return int[] Campaign IDs. */ public static function stalled_campaigns() { global $wpdb; $sends = Mailpuff_Schema::table( Mailpuff_Schema::CAMPAIGN_SENDS ); $show = $wpdb->suppress_errors(); $ids = $wpdb->get_col( $wpdb->prepare( 'SELECT DISTINCT campaign_id FROM %i WHERE status IN (%s, %s)', $sends, Mailpuff_Schema::STATUS_PENDING, Mailpuff_Schema::STATUS_PROCESSING ) ); $wpdb->suppress_errors( $show ); $stalled = array(); foreach ( (array) $ids as $id ) { if ( self::for_campaign( (int) $id )['stalled'] ) { $stalled[] = (int) $id; } } return $stalled; } /** * A campaign's batches, oldest first. * * @param int $campaign_id Campaign ID. * @return object[] */ private static function batches( $campaign_id ) { global $wpdb; $sends = Mailpuff_Schema::table( Mailpuff_Schema::CAMPAIGN_SENDS ); return (array) $wpdb->get_results( $wpdb->prepare( 'SELECT id, campaign_id, status, rate_limit, batch_size, batch_pause, created_at FROM %i WHERE campaign_id = %d ORDER BY id', $sends, (int) $campaign_id ) ); } /** * Whether a batch is still meant to send. * * @param object $batch Batch row. * @return bool */ private static function is_live( $batch ) { return in_array( $batch->status, array( Mailpuff_Schema::STATUS_PENDING, Mailpuff_Schema::STATUS_PROCESSING ), true ); } /** * Local-second times of the campaign's sends in the speed window, oldest first. * * @param int $campaign_id Campaign ID. * @param int $now Local seconds. * @return int[] */ private static function recent_sends( $campaign_id, $now ) { global $wpdb; $sends = Mailpuff_Schema::table( Mailpuff_Schema::CAMPAIGN_SENDS ); $queue = Mailpuff_Schema::table( Mailpuff_Schema::SEND_QUEUE ); $start = Mailpuff_Send_Cap::local_string( $now - self::RATE_WINDOW ); $rows = $wpdb->get_col( $wpdb->prepare( 'SELECT q.sent_at FROM %i q JOIN %i s ON s.id = q.batch_id WHERE s.campaign_id = %d AND q.sent_at > %s ORDER BY q.sent_at', $queue, $sends, (int) $campaign_id, $start ) ); return array_map( array( 'Mailpuff_Send_Cap', 'local_seconds' ), (array) $rows ); } /** * Emails a minute: from the last ten minutes of sends, or the batch's * configured speed before any send. Held to the hourly cap's pace. * * @param int[] $recent Local-second send times. * @param int $now Local seconds. * @param object|null $live The live batch. * @param array $window Mailpuff_Send_Cap::window(). * @return float */ private static function rate( array $recent, $now, $live, array $window ) { if ( ! empty( $recent ) ) { // At least a minute, so one fresh chunk does not read as a crawl. $span = max( 60, min( self::RATE_WINDOW, $now - $recent[0] ) ); $rate = count( $recent ) * 60 / $span; } elseif ( $live ) { $pause = max( 1, (int) ( $live->batch_pause ?? 0 ) ); $rate = Mailpuff_Send_Job::chunk_size( (int) ( $live->batch_size ?? 0 ), $pause, Mailpuff_Mailer::get_instance()->route()['mode'] ) * 60 / $pause; if ( $window['cap'] > 0 ) { $rate = min( $rate, $window['cap'] / 60 ); } } else { $rate = 0; } return round( (float) $rate, 1 ); } /** * When the last pending email should go, as a Unix timestamp (UTC), allowing * for the hourly cap (sends past it wait for the oldest sends of the last * hour to turn an hour old) and the daily one (sends past it wait for the * next day's room, which grows day by day during a warm-up). * * @param int $pending Emails still to send. * @param float $rate Emails a minute while sending freely. * @param array $window Mailpuff_Send_Cap::window(). * @param array $day Mailpuff_Send_Cap::day_window(). * @param int $now Local seconds. * @return int|null Null when nothing is waiting or the speed is unknown. */ private static function eta( $pending, $rate, array $window, array $day, $now ) { if ( $pending < 1 || $rate <= 0 ) { return null; } $per_sec = $rate / 60; return time() + (int) ceil( max( self::hour_delay( $pending, $per_sec, $window, $now ), self::day_delay( $pending, $per_sec, $day ) ) ); } /** * Seconds until the last pending email may go under the daily cap: what * is left in the last 24 hours goes now, then each later day takes that * day's cap (the warm-up's grows day by day). 0 when the cap does not bind. * * @param int $pending Emails still to send. * @param float $per_sec Emails a second while sending freely. * @param array $day Mailpuff_Send_Cap::day_window(). * @return float */ private static function day_delay( $pending, $per_sec, array $day ) { if ( null === $day['left'] || $pending <= $day['left'] ) { return 0; } $remaining = $pending - (int) $day['left']; $delay = Mailpuff_Send_Cap::day_reopens(); // A year of days at most: past that the estimate means nothing. for ( $i = 0; $i < 366; $i++ ) { $cap = Mailpuff_Send_Cap::effective_day( time() + $delay ); if ( $cap < 1 || $remaining <= $cap ) { return $delay + $remaining / $per_sec; } $remaining -= $cap; $delay += DAY_IN_SECONDS; } return $delay; } /** * Seconds until the last pending email may go under the hourly cap. * * @param int $pending Emails still to send. * @param float $per_sec Emails a second while sending freely. * @param array $window Mailpuff_Send_Cap::window(). * @param int $now Local seconds. * @return float */ private static function hour_delay( $pending, $per_sec, array $window, $now ) { $cap = (int) $window['cap']; if ( $cap < 1 ) { return $pending / $per_sec; } // Seconds from now to each send in the last hour turning an hour old. $aged = self::window_ages( $now ); $used = count( $aged ); $left = max( 0, $cap - $used ); $base = max( 0, $used - $cap ); // The delay for the s-th future send. The first `left` go at full speed; // every later one takes the slot a send an hour earlier frees. $delays = array(); for ( $s = 1; $s <= $pending; $s++ ) { if ( $s <= $left ) { $delays[ $s ] = $s / $per_sec; continue; } $idx = $base + ( $s - $left ) - 1; $delays[ $s ] = $idx < $used ? $aged[ $idx ] : $delays[ $idx - $used + 1 ] + HOUR_IN_SECONDS; } return max( $delays[ $pending ], $pending / $per_sec ); } /** * For each send of the last hour (any campaign), the seconds until it is an * hour old, oldest first. * * @param int $now Local seconds. * @return int[] */ private static function window_ages( $now ) { global $wpdb; $queue = Mailpuff_Schema::table( Mailpuff_Schema::SEND_QUEUE ); $start = Mailpuff_Send_Cap::local_string( $now - HOUR_IN_SECONDS ); $rows = $wpdb->get_col( $wpdb->prepare( 'SELECT sent_at FROM %i WHERE sent_at > %s ORDER BY sent_at', $queue, $start ) ); return array_map( static function ( $sent_at ) use ( $now ) { return max( 1, Mailpuff_Send_Cap::local_seconds( $sent_at ) + HOUR_IN_SECONDS - $now ); }, (array) $rows ); } /** * Whether a live batch has stopped moving: nothing sent for ten minutes, * work waiting, and its next chunk overdue by more than five minutes or * not booked at all. A wait the hourly or daily cap explains (the * warm-up's included) is not a stall. * * @param object $batch The live batch. * @param int $campaign_id Campaign ID. * @param int $now Local seconds. * @param array $window Mailpuff_Send_Cap::window(). * @param array $day Mailpuff_Send_Cap::day_window(). * @return bool */ private static function batch_stalled( $batch, $campaign_id, $now, array $window, array $day ) { global $wpdb; $sends = Mailpuff_Schema::table( Mailpuff_Schema::CAMPAIGN_SENDS ); $queue = Mailpuff_Schema::table( Mailpuff_Schema::SEND_QUEUE ); // Quiet: no send in ten minutes (a batch that never sent counts from its birth). $last = $wpdb->get_var( $wpdb->prepare( 'SELECT MAX(q.sent_at) FROM %i q JOIN %i s ON s.id = q.batch_id WHERE s.campaign_id = %d', $queue, $sends, (int) $campaign_id ) ); $last = max( $last ? Mailpuff_Send_Cap::local_seconds( $last ) : 0, $batch->created_at ? Mailpuff_Send_Cap::local_seconds( $batch->created_at ) : 0 ); if ( $now - $last < self::QUIET ) { return false; } $due = self::next_chunk_due( $batch ); // Held by the hourly or daily cap: the chunk is booked for later, which is fine. $capped = ( null !== $window['left'] && $window['left'] < 1 ) || ( null !== $day['left'] && $day['left'] < 1 ); if ( null === $due ) { return ! $capped; // Nothing booked. At the cap, that waits for the reaper. } if ( true === $due ) { return false; // A chunk is running now. } return ( time() - $due ) > self::OVERDUE; } /** * When the batch's next chunk is due. * * @param object $batch Batch row. * @return int|true|null Unix time; true while a chunk runs; null when none is booked. */ private static function next_chunk_due( $batch ) { if ( ! function_exists( 'as_next_scheduled_action' ) ) { return null; } $args = array( array( 'batch_id' => (int) $batch->id, 'campaign_id' => (int) $batch->campaign_id, ), ); $next = as_next_scheduled_action( Mailpuff_Outbox::CHUNK_HOOK, $args ); if ( false === $next ) { return null; } if ( true === $next ) { // Running, or booked to run as soon as it can (async). Read its date. $ids = ActionScheduler::store()->query_actions( array( 'hook' => Mailpuff_Outbox::CHUNK_HOOK, 'args' => $args, 'status' => ActionScheduler_Store::STATUS_PENDING, 'per_page' => 1, 'orderby' => 'date', 'order' => 'ASC', ) ); if ( empty( $ids ) ) { return true; } $date = ActionScheduler::store()->get_date( $ids[0] ); return $date ? (int) $date->getTimestamp() : true; } return (int) $next; } }