Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
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
12 changes: 10 additions & 2 deletions plugins/data-machine-events/docs/dice-fm-handler.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ The Dice FM handler (`inc/Steps/EventImport/Handlers/DiceFm/DiceFm.php`, `DiceFm
- **API Key** (`api_key`): Dice FM authentication token.
- **Include Keywords** (`search`): Comma-separated keywords to restrict imported events.
- **Exclude Keywords** (`exclude_keywords`): Skip events containing these terms.
- **Date Range** (`date_range`): Controls how far ahead the handler scans.
- **Country** (`country`): Keep only events in this country (applied across every page). Defaults to United States.
- **Max Events Per Run** (`max_items`): New events sent downstream per run, nearest dates first. Defaults to 100; 0 = unlimited.
- **Horizon (days)** (`horizon_days`): Stop paginating once date-sorted results pass this many days out. 0 (default) = every upcoming event.

## Data Mapping

Expand All @@ -20,7 +22,13 @@ The Dice FM handler (`inc/Steps/EventImport/Handlers/DiceFm/DiceFm.php`, `DiceFm

## Unique Capabilities

Dice FM delivers curated gig data with keyword filtering, city-specific scopes, and classification support straight from the public JSON API. The handler is optimized for large result sets by requesting 100 events per page yet still stopping after the first suitable event to avoid timeouts.
Dice FM delivers curated gig data with keyword filtering, city-specific scopes, and classification support straight from the public JSON API.

## Pagination

The partner API is sorted by date and returns 100 events per page. The handler follows `links.next` (incrementing `page[number]`) until the API stops returning one, the configured horizon is passed, or `DiceFm::MAX_PAGES` (80) is reached. Hitting the page cap logs a fetch-stage warning: `DiceFm: Query exceeds pagination cap; events will be truncated`. A failed later page keeps the events from earlier pages.

Already-processed items are skipped by processed-item tracking, then `max_items` takes the nearest-dated unprocessed events. A big city's first run therefore fills the next few weeks first and drains the rest of the backlog over later runs (London is about 5k events, 54 pages).

## Event Handoff

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,26 @@ class DiceFm extends EventImportHandler {

use HandlerRegistrationTrait;

/** Events requested per Dice partner API page. */
const PAGE_SIZE = 100;

/**
* Hard ceiling on pages fetched in one run.
*
* London, the largest Dice city we import, is about 54 pages of 100.
* The cap keeps a runaway `links.next` chain from exploding a run.
*/
const MAX_PAGES = 80;

/**
* Default per-run fan-out bound.
*
* Every Dice item goes through an AI step, so a big-city backlog
* (London is about 5k events) drains over several runs, nearest
* dates first, instead of in a single run.
*/
const DEFAULT_MAX_ITEMS = 100;

public function __construct() {
parent::__construct( 'dice_fm' );

Expand All @@ -50,9 +70,18 @@ protected function getSourceInventoryCapabilities(): array {
'stable_ids' => true,
'supports_query_shards' => true,
'bounded_by' => array( 'city', 'country' ),
'pagination' => 'page',
'max_pages' => self::MAX_PAGES,
);
}

/**
* Bound each run's fan-out so big-city backlogs drain nearest-first.
*/
protected function getDefaultMaxItems(): int {
return self::DEFAULT_MAX_ITEMS;
}

/**
* Execute Dice FM event import with flat parameter structure
*/
Expand Down Expand Up @@ -85,8 +114,10 @@ protected function executeFetch( array $config, ExecutionContext $context ): arr
// Build configuration
$partner_id = ! empty( $api_config['partner_id'] ) ? trim( $api_config['partner_id'] ) : '';

$horizon_days = max( 0, (int) ( $config['horizon_days'] ?? 0 ) );

// Fetch events from API
$raw_events = $this->fetch_dice_fm_events( $api_config['api_key'], $city, $partner_id, $context );
$raw_events = $this->fetch_dice_fm_events( $api_config['api_key'], $city, $partner_id, $context, $horizon_days );
if ( empty( $raw_events ) ) {
$context->log( 'info', 'DiceFm: No events found from API' );
return array();
Expand Down Expand Up @@ -135,7 +166,7 @@ protected function executeFetch( array $config, ExecutionContext $context ): arr
$event_identifier = $source_identity['event_identifier'];

$context->log(
'info',
'debug',
'DiceFm: Found eligible event',
array(
'title' => $standardized_event['title'],
Expand Down Expand Up @@ -187,6 +218,10 @@ protected function executeFetch( array $config, ExecutionContext $context ): arr
return array();
}

// Nearest dates first: the max_items throttle slices from the front, so
// a large backlog fills the next few weeks before far-future dates.
$eligible_items = self::sortItemsByStart( $eligible_items );

$context->log(
'info',
sprintf( 'DiceFm: Found %d eligible events', count( $eligible_items ) ),
Expand All @@ -197,21 +232,51 @@ protected function executeFetch( array $config, ExecutionContext $context ): arr
}

/**
* Fetch events from Dice.fm API
* Sort eligible items by event start, nearest first (stable).
*
* @param array $items Eligible items with `_engine_data` metadata.
* @return array Sorted items.
*/
private function fetch_dice_fm_events( $api_key, $city, $partner_id, ExecutionContext $context ): array {
$base_url = 'https://partners-endpoint.dice.fm/api/v2/events';
public static function sortItemsByStart( array $items ): array {
$keyed = array();
foreach ( array_values( $items ) as $index => $item ) {
$event = $item['metadata']['_engine_data'] ?? array();
$start = trim( ( $event['startDate'] ?? '' ) . ' ' . ( $event['startTime'] ?? '' ) );
$keyed[] = array(
'key' => '' !== $start ? $start : '9999-12-31',
'index' => $index,
'item' => $item,
);
}

// Build query parameters
$params = array(
'page[size]' => 100,
'types' => 'linkout,event',
'filter[cities][]' => $city,
usort(
$keyed,
static function ( array $a, array $b ): int {
$cmp = strcmp( $a['key'], $b['key'] );
return 0 !== $cmp ? $cmp : $a['index'] <=> $b['index'];
}
);

$url = add_query_arg( $params, $base_url );
return array_column( $keyed, 'item' );
}

/**
* Fetch every upcoming event for a city from the Dice.fm partner API.
*
* Follows `links.next` by incrementing `page[number]` until the API stops
* returning a next link, the page cap is reached, or (when a horizon is
* configured) the date-sorted results move past the horizon.
*
* @param string $api_key Partner API key.
* @param string $city City filter.
* @param string $partner_id Optional partner ID.
* @param ExecutionContext $context Execution context for logging.
* @param int $horizon_days Only fetch events starting within this many days (0 = no horizon).
* @return array Raw Dice event arrays.
*/
private function fetch_dice_fm_events( $api_key, $city, $partner_id, ExecutionContext $context, int $horizon_days = 0 ): array {
$base_url = 'https://partners-endpoint.dice.fm/api/v2/events';

// Prepare headers
$headers = array(
'Accept' => 'application/json',
'x-api-key' => $api_key,
Expand All @@ -221,7 +286,92 @@ private function fetch_dice_fm_events( $api_key, $city, $partner_id, ExecutionCo
$headers['X-Partner-Id'] = trim( $partner_id );
}

// Make API request
$horizon_ts = $horizon_days > 0 ? time() + ( $horizon_days * DAY_IN_SECONDS ) : 0;
$events = array();
$page = 1;
$fetched = 0;
$has_next = false;

do {
$params = array(
'page[size]' => self::PAGE_SIZE,
'page[number]' => $page,
'types' => 'linkout,event',
'filter[cities][]' => $city,
);

$data = $this->request_dice_page( add_query_arg( $params, $base_url ), $headers, $context, $page );
if ( null === $data ) {
// Keep whatever earlier pages returned; later runs pick up the rest.
break;
}

++$fetched;
$page_events = $data['data'];
$has_next = ! empty( $data['links']['next'] ) && ! empty( $page_events );

$past_horizon = false;
foreach ( $page_events as $event ) {
if ( $horizon_ts > 0 && ! empty( $event['date'] ) ) {
$event_ts = strtotime( (string) $event['date'] );
if ( false !== $event_ts && $event_ts > $horizon_ts ) {
$past_horizon = true;
continue;
}
}
$events[] = $event;
}

if ( $past_horizon && $has_next ) {
// Dice sorts by date, so every later page is past the horizon too.
$context->log(
'info',
'DiceFm: Pagination stopped at configured horizon',
array(
'city' => $city,
'pages' => $page,
'horizon_days' => $horizon_days,
)
);
break;
}

if ( $has_next && $page >= self::MAX_PAGES ) {
$context->log(
'warning',
'DiceFm: Query exceeds pagination cap; events will be truncated',
array(
'city' => $city,
'pages_fetched' => $page,
'max_pages' => self::MAX_PAGES,
'events' => count( $events ),
)
);
break;
}

++$page;
} while ( $has_next );

$context->log(
'info',
'DiceFm: Pagination complete',
array(
'city' => $city,
'pages' => $fetched,
'events' => count( $events ),
)
);

return $events;
}

/**
* Request and decode one Dice partner API page.
*
* @return array|null Decoded body with a `data` list, or null on failure.
*/
private function request_dice_page( string $url, array $headers, ExecutionContext $context, int $page ): ?array {
$result = $this->httpGet(
$url,
array(
Expand All @@ -231,31 +381,36 @@ private function fetch_dice_fm_events( $api_key, $city, $partner_id, ExecutionCo
);

if ( ! $result['success'] ) {
$context->log( 'error', 'DiceFm: API request failed', array( 'error' => $result['error'] ?? 'Unknown error' ) );
return array();
$context->log(
'error',
'DiceFm: API request failed',
array(
'error' => $result['error'] ?? 'Unknown error',
'page' => $page,
)
);
return null;
}

$response_code = $result['status_code'];
$body = $result['data'];

if ( 200 !== $response_code ) {
$context->log( 'error', 'DiceFm: API returned status ' . $response_code );
return array();
$context->log( 'error', 'DiceFm: API returned status ' . $response_code, array( 'page' => $page ) );
return null;
}

$data = json_decode( $body, true );
$data = json_decode( $result['data'], true );

if ( json_last_error() !== JSON_ERROR_NONE ) {
$context->log( 'error', 'DiceFm: Invalid JSON response from API' );
return array();
$context->log( 'error', 'DiceFm: Invalid JSON response from API', array( 'page' => $page ) );
return null;
}

if ( ! isset( $data['data'] ) || ! is_array( $data['data'] ) ) {
$context->log( 'error', 'DiceFm: No events data in response' );
return array();
$context->log( 'error', 'DiceFm: No events data in response', array( 'page' => $page ) );
return null;
}

return $data['data'];
return $data;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,25 @@ public static function get_fields( array $current_config = array() ): array {
),
);

$limit_fields = array(
'max_items' => array(
'type' => 'number',
'label' => __( 'Max Events Per Run', 'data-machine-events' ),
'description' => __( 'Maximum new events sent downstream per run, nearest dates first. Large cities drain their backlog over several runs. 0 = unlimited.', 'data-machine-events' ),
'default' => DiceFm::DEFAULT_MAX_ITEMS,
'min' => 0,
'required' => false,
),
'horizon_days' => array(
'type' => 'number',
'label' => __( 'Horizon (days)', 'data-machine-events' ),
'description' => __( 'Only fetch events starting within this many days. 0 = every upcoming event the source offers (bounded by the page cap).', 'data-machine-events' ),
'default' => 0,
'min' => 0,
'required' => false,
),
);

$filter_fields = array(
'search' => array(
'type' => 'text',
Expand All @@ -62,7 +81,7 @@ public static function get_fields( array $current_config = array() ): array {
),
);

return array_merge( $handler_fields, $filter_fields );
return array_merge( $handler_fields, $limit_fields, $filter_fields );
}

/**
Expand All @@ -77,6 +96,8 @@ public static function sanitize( array $raw_settings ): array {
'country' => sanitize_text_field( $raw_settings['country'] ?? '' ),
'search' => sanitize_text_field( $raw_settings['search'] ?? '' ),
'exclude_keywords' => sanitize_text_field( $raw_settings['exclude_keywords'] ?? '' ),
'max_items' => absint( $raw_settings['max_items'] ?? DiceFm::DEFAULT_MAX_ITEMS ),
'horizon_days' => absint( $raw_settings['horizon_days'] ?? 0 ),
);
}

Expand All @@ -101,6 +122,8 @@ public static function get_defaults(): array {
'country' => 'United States',
'search' => '',
'exclude_keywords' => '',
'max_items' => DiceFm::DEFAULT_MAX_ITEMS,
'horizon_days' => 0,
);
}
}
Loading
Loading