Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
83fdde5
feat: add ActionScheduler group helper methods
miguelpeixe Mar 11, 2026
b75e46c
feat: use per-integration AS group for handler retries
miguelpeixe Mar 11, 2026
9be6dec
feat: use per-integration AS group for sync retries
miguelpeixe Mar 11, 2026
a5bbe44
feat: use per-integration AS group for async pulls
miguelpeixe Mar 11, 2026
27ba501
feat: use dedicated AS group for webhook actions
miguelpeixe Mar 11, 2026
c579f10
fix: explicitly set AS group for bulk sync actions
miguelpeixe Mar 11, 2026
dc11ece
feat: add get_scheduled_actions query helper for UI
miguelpeixe Mar 11, 2026
e3bd456
test: update sync tests to use per-integration AS groups
miguelpeixe Mar 11, 2026
95cff00
feat: add action group shortcuts to Integration base class
miguelpeixe Mar 11, 2026
81e22b2
fix: make action methods final
miguelpeixe Mar 11, 2026
30b7366
feat: decouple integrations from data events handler action group name
miguelpeixe Mar 11, 2026
be1aef1
chore: remove default action group constant and update fallback behavior
miguelpeixe Mar 11, 2026
bdff70e
docs: update return type
miguelpeixe Mar 11, 2026
2be5e66
feat: introduce ActionScheduler class and integrate with existing com…
miguelpeixe Mar 11, 2026
f7a7c1f
chore: move init up
miguelpeixe Mar 11, 2026
b4e1ec2
feat: return empty array for empty groups in get_scheduled_actions
miguelpeixe Mar 11, 2026
1ef00a7
refactor: optimize get_scheduled_actions query
miguelpeixe Mar 11, 2026
cda43b6
chore: fix docblock
miguelpeixe Mar 11, 2026
43cdbc2
chore: fix docblock
miguelpeixe Mar 11, 2026
a95cf5a
feat: add is_available method and handle availability checks
miguelpeixe Mar 11, 2026
caa12e5
refactor: streamline SQL query preparation
miguelpeixe Mar 11, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
128 changes: 128 additions & 0 deletions includes/class-action-scheduler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
<?php
/**
* ActionScheduler utilities.
*
* @package Newspack
*/

namespace Newspack;

defined( 'ABSPATH' ) || exit;

/**
* General-purpose ActionScheduler helpers for Newspack.
*/
class Action_Scheduler {
/**
* Default ActionScheduler group for Newspack actions.
*/
const DEFAULT_GROUP = 'newspack';

/**
* Prefix for Newspack ActionScheduler groups.
*/
const GROUP_PREFIX = 'newspack-';

/**
* Whether ActionScheduler is available.
*
* @return bool
*/
public static function is_available() {
return class_exists( 'ActionScheduler' );
}

/**
* Get ActionScheduler group slugs matching a prefix.
*
* @param string $prefix The prefix to match (e.g. 'newspack-').
*
* @return string[] Array of group slug strings.
*/
public static function get_groups_by_prefix( $prefix ) {
if ( ! self::is_available() ) {
return [];
}
global $wpdb;
$table = $wpdb->prefix . 'actionscheduler_groups';
return $wpdb->get_col( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$wpdb->prepare(
"SELECT slug FROM {$table} WHERE slug LIKE %s", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$wpdb->esc_like( $prefix ) . '%'
)
);
}

/**
* Query ActionScheduler actions by group slugs.
*
* @param array $args {
* Query arguments.
*
* @type string[] $groups Array of group slugs to query.
* @type string $status ActionScheduler status (pending, complete, failed, canceled).
* @type int $per_page Number of actions to return. Default 20.
* @type int $offset Offset for pagination. Default 0.
* @type string $orderby Column to order by. Default 'scheduled_date_gmt'.
* @type string $order ASC or DESC. Default 'DESC'.
* }
*
* @return array Array of action row objects.
*/
public static function get_scheduled_actions( $args = [] ) {
if ( ! self::is_available() ) {
return [];
}
global $wpdb;

$defaults = [
'groups' => [],
'status' => '',
'per_page' => 20,
'offset' => 0,
'orderby' => 'scheduled_date_gmt',
'order' => 'DESC',
];
$args = wp_parse_args( $args, $defaults );

$slugs = $args['groups'];
if ( empty( $slugs ) ) {
$slugs = array_merge(
[ self::DEFAULT_GROUP ],
self::get_groups_by_prefix( self::GROUP_PREFIX )
);
}
if ( empty( $slugs ) ) {
return [];
}

$allowed_orderby = [ 'scheduled_date_gmt', 'action_id', 'hook', 'status' ];
$orderby = in_array( $args['orderby'], $allowed_orderby, true ) ? $args['orderby'] : 'scheduled_date_gmt';
$order = 'ASC' === strtoupper( $args['order'] ) ? 'ASC' : 'DESC';

$actions_table = $wpdb->prefix . 'actionscheduler_actions';
$groups_table = $wpdb->prefix . 'actionscheduler_groups';
$slug_placeholders = implode( ',', array_fill( 0, count( $slugs ), '%s' ) );
$prepare_args = $slugs;

// Build optional status filter.
$status_clause = '';
if ( ! empty( $args['status'] ) ) {
$status_clause = 'AND a.status = %s ';
$prepare_args[] = $args['status'];
}

$prepare_args[] = absint( $args['per_page'] );
$prepare_args[] = absint( $args['offset'] );

// Table names: $wpdb->prefix + hardcoded strings. $orderby/$order: allowlist/ternary validated.
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$sql = "SELECT a.* FROM {$actions_table} a INNER JOIN {$groups_table} g ON a.group_id = g.group_id WHERE g.slug IN ({$slug_placeholders}) {$status_clause}ORDER BY a.{$orderby} {$order} LIMIT %d OFFSET %d";

// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber
$query = $wpdb->prepare( $sql, ...$prepare_args );

// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared
return $wpdb->get_results( $query );
}
}
1 change: 1 addition & 0 deletions includes/class-newspack.php
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ private function includes() {
include_once NEWSPACK_ABSPATH . 'includes/reader-activation/sync/class-woocommerce.php';
include_once NEWSPACK_ABSPATH . 'includes/reader-activation/sync/class-contact-sync.php';
include_once NEWSPACK_ABSPATH . 'includes/reader-activation/sync/class-contact-sync-admin.php';
include_once NEWSPACK_ABSPATH . 'includes/class-action-scheduler.php';
include_once NEWSPACK_ABSPATH . 'includes/reader-activation/class-integrations.php';
\Newspack\Reader_Activation\Integrations::init();
include_once NEWSPACK_ABSPATH . 'includes/data-events/class-utils.php';
Expand Down
31 changes: 29 additions & 2 deletions includes/data-events/class-data-events.php
Original file line number Diff line number Diff line change
Expand Up @@ -624,6 +624,28 @@ public static function execute_queued_dispatches() {
self::$queued_dispatches = [];
}

/**
* Get the ActionScheduler group for a handler.
*
* Returns a filterable default of 'newspack'. Integrations or other
* systems can filter this to assign handlers to specific groups.
*
* @param string $class The handler class name.
* @param string $action_name The data event action name.
*
* @return string The ActionScheduler group name.
*/
public static function get_handler_action_group( $class, $action_name ) {
/**
* Filters the ActionScheduler group for a data event handler.
*
* @param string $group The group name. Default 'newspack'.
* @param string $class The handler class name.
* @param string $action_name The data event action name.
*/
return \apply_filters( 'newspack_data_events_handler_action_group', Action_Scheduler::DEFAULT_GROUP, $class, $action_name );
}

/**
* Dispatch queued events via Action Scheduler.
*
Expand All @@ -634,7 +656,7 @@ private static function dispatch_via_action_scheduler() {
\as_enqueue_async_action(
self::DISPATCH_AS_HOOK,
[ self::$queued_dispatches ],
'newspack'
Action_Scheduler::DEFAULT_GROUP
);

self::log( sprintf( 'Scheduled %d dispatch(es) via Action Scheduler.', count( self::$queued_dispatches ) ) );
Expand Down Expand Up @@ -810,11 +832,16 @@ private static function schedule_handler_retry( $handler, $action_name, $timesta
'reason' => $error->getMessage(),
];

$group = self::get_handler_action_group(
is_array( $handler ) ? $handler[0] : '',
$action_name
);

$action_id = \as_schedule_single_action(
time() + $backoff_seconds,
self::HANDLER_RETRY_HOOK,
[ $retry_data ],
'newspack'
$group
);

if ( $action_id ) {
Expand Down
2 changes: 1 addition & 1 deletion includes/data-events/class-webhooks.php
Original file line number Diff line number Diff line change
Expand Up @@ -732,7 +732,7 @@ private static function schedule_request( $request_id, $delay = 1 ) {
$time,
'newspack_webhooks_as_process_request',
[ $request_id ],
'newspack',
'newspack-webhooks',
false,
self::get_request_priority( $request_id )
);
Expand Down
95 changes: 95 additions & 0 deletions includes/reader-activation/class-integrations.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,105 @@ public static function init() {
add_action( 'init', [ __CLASS__, 'register_integrations' ], 5 );
add_action( 'init', [ __CLASS__, 'schedule_health_check' ] );
add_action( self::HEALTH_CHECK_CRON_HOOK, [ __CLASS__, 'run_health_checks' ] );
add_filter( 'newspack_data_events_handler_action_group', [ __CLASS__, 'filter_handler_action_group' ], 10, 3 );

Integrations\Contact_Pull::init();
}

/**
* Get the ActionScheduler group name for a specific integration.
*
* @param string $integration_id The integration ID.
*
* @return string The group name (e.g., 'newspack-integration-esp').
*/
public static function get_action_group( $integration_id ) {
return \Newspack\Action_Scheduler::GROUP_PREFIX . 'integration-' . $integration_id;
}

/**
* Resolve the ActionScheduler group for a data event handler.
*
* Looks up the handler in the internal handler map and returns the
* per-integration group, or null if the handler is not registered
* through an integration.
*
* @param string $class The handler class name.
* @param string $action_name The data event action name.
*
* @return string|null The group name or null if the handler is not registered through an integration.
*/
public static function get_action_group_for_handler( $class, $action_name ) {
$key = $class . '::' . $action_name;
if ( isset( self::$handler_map[ $key ] ) ) {
return self::get_action_group( self::$handler_map[ $key ]['integration_id'] );
}
return null;
}

/**
* Filter the ActionScheduler group for a data event handler.
*
* Hooked to 'newspack_data_events_handler_action_group' to assign
* integration-specific groups to handlers registered through integrations.
*
* @param string $group The default group name.
* @param string $class The handler class name.
* @param string $action_name The data event action name.
*
* @return string The filtered group name.
*/
public static function filter_handler_action_group( $group, $class, $action_name ) {
return self::get_action_group_for_handler( $class, $action_name ) ?? $group;
}

/**
* Get all ActionScheduler group slugs for Newspack integrations.
*
* @return string[] Array of group slug strings.
*/
public static function get_all_action_groups() {
return \Newspack\Action_Scheduler::get_groups_by_prefix( \Newspack\Action_Scheduler::GROUP_PREFIX . 'integration-' );
}

/**
* Get ActionScheduler actions for Newspack integrations.
*
* @param array $args {
* Optional. Query arguments.
*
* @type string $integration_id Filter by a single integration ID.
* @type string $status ActionScheduler status (pending, complete, failed, canceled).
* @type int $per_page Number of actions to return. Default 20.
* @type int $offset Offset for pagination. Default 0.
* @type string $orderby Column to order by. Default 'scheduled_date_gmt'.
* @type string $order ASC or DESC. Default 'DESC'.
* }
*
* @return array Array of action row objects.
*/
public static function get_scheduled_actions( $args = [] ) {
$defaults = [
'integration_id' => '',
];
$args = wp_parse_args( $args, $defaults );

// Resolve integration_id to group slugs.
if ( ! empty( $args['integration_id'] ) ) {
$args['groups'] = [ self::get_action_group( $args['integration_id'] ) ];
} else {
$args['groups'] = self::get_all_action_groups();
}
unset( $args['integration_id'] );

// No groups to query, return empty array.
if ( empty( $args['groups'] ) ) {
return [];
}

return \Newspack\Action_Scheduler::get_scheduled_actions( $args );
}

/**
* Register integrations.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -287,14 +287,16 @@ private static function schedule_async_pulls( $user_id, $integrations ) {
],
];

if ( function_exists( 'as_has_scheduled_action' ) && \as_has_scheduled_action( self::ASYNC_PULL_HOOK, $args, 'newspack' ) ) {
$group = Integrations::get_action_group( $integration->get_id() );

if ( function_exists( 'as_has_scheduled_action' ) && \as_has_scheduled_action( self::ASYNC_PULL_HOOK, $args, $group ) ) {
continue;
}

\as_enqueue_async_action(
self::ASYNC_PULL_HOOK,
$args,
'newspack'
$group
);
}
}
Expand Down
21 changes: 21 additions & 0 deletions includes/reader-activation/integrations/class-integration.php
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,27 @@ final public function health_check() {
return true;
}

/**
* Get the ActionScheduler group name for this integration.
*
* @return string The group name (e.g., 'newspack-integration-esp').
*/
final public function get_action_group() {
return Integrations::get_action_group( $this->id );
}

/**
* Get ActionScheduler actions for this integration.
*
* @param array $args Optional. Query arguments (status, per_page, offset, orderby, order).
*
* @return array Array of action row objects.
*/
final public function get_scheduled_actions( $args = [] ) {
$args['integration_id'] = $this->id;
return Integrations::get_scheduled_actions( $args );
}

/**
* Get the enabled outgoing metadata fields for this integration.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ public static function handle_bulk_actions( $sendback, $doaction, $items ) {
\wp_die( \esc_html__( 'You do not have permission to do that.', 'newspack-plugin' ) );
}
foreach ( $items as $user_id ) {
as_schedule_single_action( time(), 'newspack_sync_admin_batch', [ 'user_id' => $user_id ] );
as_schedule_single_action( time(), 'newspack_sync_admin_batch', [ 'user_id' => $user_id ], 'newspack-sync' );
}
$sendback = \add_query_arg(
[
Expand Down
2 changes: 1 addition & 1 deletion includes/reader-activation/sync/class-contact-sync.php
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ private static function schedule_integration_retry( $integration_id, $contact, $
time() + $backoff_seconds,
self::RETRY_HOOK,
[ $retry_data ],
'newspack'
Integrations::get_action_group( $integration_id )
);

static::log(
Expand Down
Loading
Loading