diff --git a/plugins/data-machine-events/docs/dice-fm-handler.md b/plugins/data-machine-events/docs/dice-fm-handler.md index e04a47a99..a74039674 100644 --- a/plugins/data-machine-events/docs/dice-fm-handler.md +++ b/plugins/data-machine-events/docs/dice-fm-handler.md @@ -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 @@ -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 diff --git a/plugins/data-machine-events/inc/Steps/EventImport/Handlers/DiceFm/DiceFm.php b/plugins/data-machine-events/inc/Steps/EventImport/Handlers/DiceFm/DiceFm.php index d10965480..0a272da8a 100644 --- a/plugins/data-machine-events/inc/Steps/EventImport/Handlers/DiceFm/DiceFm.php +++ b/plugins/data-machine-events/inc/Steps/EventImport/Handlers/DiceFm/DiceFm.php @@ -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' ); @@ -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 */ @@ -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(); @@ -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'], @@ -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 ) ), @@ -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, @@ -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( @@ -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; } /** diff --git a/plugins/data-machine-events/inc/Steps/EventImport/Handlers/DiceFm/DiceFmSettings.php b/plugins/data-machine-events/inc/Steps/EventImport/Handlers/DiceFm/DiceFmSettings.php index 6b46c3510..c12ad8199 100644 --- a/plugins/data-machine-events/inc/Steps/EventImport/Handlers/DiceFm/DiceFmSettings.php +++ b/plugins/data-machine-events/inc/Steps/EventImport/Handlers/DiceFm/DiceFmSettings.php @@ -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', @@ -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 ); } /** @@ -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 ), ); } @@ -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, ); } } diff --git a/plugins/data-machine-events/inc/Steps/EventImport/Handlers/Ticketmaster/Ticketmaster.php b/plugins/data-machine-events/inc/Steps/EventImport/Handlers/Ticketmaster/Ticketmaster.php index 0e8b3e2ca..6aeee12b4 100644 --- a/plugins/data-machine-events/inc/Steps/EventImport/Handlers/Ticketmaster/Ticketmaster.php +++ b/plugins/data-machine-events/inc/Steps/EventImport/Handlers/Ticketmaster/Ticketmaster.php @@ -41,6 +41,15 @@ class Ticketmaster extends EventImportHandler { const MAX_PAGE = 19; + /** + * Maximum consecutive date windows one geo query is split into when its + * totalElements exceeds the deep-paging reach (#4108). + */ + const MAX_DATE_WINDOWS = 12; + + /** First date-window span tried when splitting a geo query, in days. */ + const INITIAL_WINDOW_DAYS = 14; + /** Maximum attraction IDs in one artist-mode Discovery query. */ const ATTRACTION_IDS_PER_QUERY = 25; @@ -211,7 +220,13 @@ protected function executeFetch( array $config, ExecutionContext $context ): arr $repeated_source_count = 0; $contended_count = 0; - foreach ( $query_shards as $search_params ) { + $shard_queue = $query_shards; + $shards_fetched = 0; + $windowed = false; + + while ( ! empty( $shard_queue ) ) { + $search_params = array_shift( $shard_queue ); + ++$shards_fetched; $current_page = 0; do { $search_params['page'] = $current_page; @@ -222,6 +237,27 @@ protected function executeFetch( array $config, ExecutionContext $context ): arr $reachable_count = ( self::MAX_PAGE + 1 ) * (int) $search_params['size']; if ( 0 === $current_page && (int) ( $page_info['totalElements'] ?? 0 ) > $reachable_count ) { + if ( ! $windowed && ! isset( $search_params['attractionId'] ) ) { + // Geo mode: split into consecutive date windows that each + // fit under the deep-paging reach, nearest dates first. + $windowed = true; + $windows = $this->plan_date_windows( $search_params, $reachable_count, $context ); + if ( count( $windows ) > 1 ) { + $context->log( + 'info', + 'Ticketmaster: Geo query exceeds pagination cap; splitting into date windows', + array( + 'total_elements' => (int) $page_info['totalElements'], + 'reachable_count' => $reachable_count, + 'windows' => count( $windows ), + ) + ); + --$shards_fetched; + $shard_queue = array_merge( $windows, $shard_queue ); + break; + } + } + $context->log( 'warning', 'Ticketmaster: Query exceeds pagination cap; events will be truncated', @@ -229,6 +265,8 @@ protected function executeFetch( array $config, ExecutionContext $context ): arr 'total_elements' => (int) $page_info['totalElements'], 'reachable_count' => $reachable_count, 'attraction_ids' => $search_params['attractionId'] ?? '', + 'start_date_time' => $search_params['startDateTime'] ?? '', + 'end_date_time' => $search_params['endDateTime'] ?? '', ) ); } @@ -365,7 +403,7 @@ protected function executeFetch( array $config, ExecutionContext $context ): arr } while ( $has_more_pages ); } - if ( count( $query_shards ) > 1 ) { + if ( $shards_fetched > 1 ) { // Merge API-sorted shards before bounding fan-out so later shards // are not starved by more distant events in the first shard. usort( @@ -491,6 +529,89 @@ static function ( array $a, array $b ): int { return array( 'items' => $eligible_items ); } + /** + * Split a geo query into consecutive date windows under the paging reach. + * + * Walks forward from the query's startDateTime, nearest dates first. Each + * window is probed for totalElements (size=1) and halved until it fits or + * reaches one day; the span grows again after sparse windows. Once the + * remaining open-ended tail fits, it becomes the last window. A window that + * still exceeds the reach at one day, or a tail left over after + * MAX_DATE_WINDOWS, is paginated as far as the API allows and logged by the + * caller's pagination-cap warning. + * + * @param array $params Base geo search params (with startDateTime). + * @param int $reachable Events reachable through deep paging. + * @param ExecutionContext $context Execution context. + * @return array[] Search params per window, chronological. + */ + private function plan_date_windows( array $params, int $reachable, ExecutionContext $context ): array { + $cursor = strtotime( (string) ( $params['startDateTime'] ?? '' ) ); + if ( false === $cursor ) { + $cursor = time(); + } + + $span = self::INITIAL_WINDOW_DAYS * DAY_IN_SECONDS; + $windows = array(); + + for ( $planned = 0; $planned < self::MAX_DATE_WINDOWS - 1; $planned++ ) { + if ( $this->probe_total( $params, $cursor, null, $context ) <= $reachable ) { + $windows[] = $this->window_params( $params, $cursor, null ); + return $windows; + } + + do { + $total = $this->probe_total( $params, $cursor, $cursor + $span - 1, $context ); + if ( $total <= $reachable || $span <= DAY_IN_SECONDS ) { + break; + } + $span = max( DAY_IN_SECONDS, intdiv( $span, 2 ) ); + } while ( true ); + + $windows[] = $this->window_params( $params, $cursor, $cursor + $span - 1 ); + $cursor += $span; + + if ( $total * 2 < $reachable ) { + $span *= 2; + } + } + + $context->log( + 'warning', + 'Ticketmaster: Date window cap reached; remaining dates use one open-ended window', + array( + 'max_windows' => self::MAX_DATE_WINDOWS, + 'start_date_time' => gmdate( 'Y-m-d\TH:i:s\Z', $cursor ), + ) + ); + $windows[] = $this->window_params( $params, $cursor, null ); + + return $windows; + } + + /** + * Build search params for one date window. + */ + private function window_params( array $params, int $start, ?int $end ): array { + $params['page'] = 0; + $params['startDateTime'] = gmdate( 'Y-m-d\TH:i:s\Z', $start ); + unset( $params['endDateTime'] ); + if ( null !== $end ) { + $params['endDateTime'] = gmdate( 'Y-m-d\TH:i:s\Z', $end ); + } + return $params; + } + + /** + * Read totalElements for a date window with a one-result request. + */ + private function probe_total( array $params, int $start, ?int $end, ExecutionContext $context ): int { + $probe = $this->window_params( $params, $start, $end ); + $probe['size'] = 1; + $result = $this->fetch_events( $probe, $context ); + return (int) ( $result['page']['totalElements'] ?? 0 ); + } + /** * Build search parameters for API request */ diff --git a/plugins/data-machine-events/tests/Unit/DiceFmPaginationTest.php b/plugins/data-machine-events/tests/Unit/DiceFmPaginationTest.php new file mode 100644 index 000000000..df2abd850 --- /dev/null +++ b/plugins/data-machine-events/tests/Unit/DiceFmPaginationTest.php @@ -0,0 +1,258 @@ + Query args for each mocked request. */ + private array $queries = array(); + + /** @var array Logged warnings/info messages. */ + private array $logs = array(); + + public function setUp(): void { + parent::setUp(); + ( new ProcessedItems() )->create_table(); + $this->queries = array(); + $this->logs = array(); + add_action( 'datamachine_log', array( $this, 'captureLog' ), 10, 3 ); + } + + public function tearDown(): void { + remove_action( 'datamachine_log', array( $this, 'captureLog' ), 10 ); + remove_all_filters( 'pre_http_request' ); + parent::tearDown(); + } + + public function captureLog( string $level, string $message, array $context = array() ): void { + $this->logs[] = array( + 'level' => $level, + 'message' => $message, + 'context' => $context, + ); + } + + public function test_follows_links_next_across_all_pages(): void { + $this->mockDice( 3, 2 ); + + $packets = $this->fetch( array( 'max_items' => 0 ) ); + + $this->assertCount( 6, $packets ); + $this->assertSame( array( '1', '2', '3' ), array_column( $this->queries, 'page[number]' ) ); + foreach ( $this->queries as $query ) { + $this->assertSame( (string) DiceFm::PAGE_SIZE, $query['page[size]'] ); + $this->assertSame( 'London', $query['filter']['cities'][0] ?? '' ); + } + $this->assertEmpty( $this->logsMatching( 'pagination cap' ) ); + } + + public function test_page_cap_stops_and_logs_fetch_stage_warning(): void { + $this->mockDice( DiceFm::MAX_PAGES + 5, 1 ); + + $packets = $this->fetch( array( 'max_items' => 0 ) ); + + $this->assertCount( DiceFm::MAX_PAGES, $this->queries ); + $this->assertCount( DiceFm::MAX_PAGES, $packets ); + $warnings = $this->logsMatching( 'pagination cap' ); + $this->assertCount( 1, $warnings ); + $this->assertSame( 'warning', $warnings[0]['level'] ); + $this->assertSame( DiceFm::MAX_PAGES, $warnings[0]['context']['max_pages'] ); + } + + public function test_horizon_stops_paging_once_results_pass_it(): void { + // 10 pages, one event per page, each a week further out. + $this->mockDice( 10, 1, 7 ); + + $packets = $this->fetch( + array( + 'max_items' => 0, + 'horizon_days' => 20, + ) + ); + + // Events at +1d, +8d, +15d are inside; +22d stops pagination on page 4. + $this->assertCount( 3, $packets ); + $this->assertCount( 4, $this->queries ); + $this->assertCount( 1, $this->logsMatching( 'configured horizon' ) ); + $this->assertEmpty( $this->logsMatching( 'pagination cap' ) ); + } + + public function test_country_filter_applies_across_pages(): void { + $this->mockDice( + 3, + 2, + 1, + static fn( int $page, int $index ): string => 1 === $index ? 'United States' : 'United Kingdom' + ); + + $packets = $this->fetch( array( 'max_items' => 0 ) ); + + $this->assertCount( 3, $packets ); + $this->assertCount( 3, $this->queries ); + foreach ( $packets as $packet ) { + $body = json_decode( $packet->addTo( array() )[0]['data']['body'], true ); + $this->assertSame( 'United Kingdom', $body['venue_metadata']['venueCountry'] ); + } + } + + public function test_max_items_selects_nearest_dates_first(): void { + // Pages return far-out events first to prove the handler sorts itself. + $this->mockDice( 3, 2, -1 ); + + $packets = $this->fetch( array( 'max_items' => 2 ) ); + + $this->assertCount( 2, $packets ); + $this->assertCount( 3, $this->queries ); + $titles = array_map( + static fn( $packet ): string => $packet->addTo( array() )[0]['metadata']['original_title'], + $packets + ); + $this->assertSame( array( 'Dice Show p3-2', 'Dice Show p3-1' ), $titles ); + } + + public function test_default_max_items_bounds_first_backfill(): void { + $this->assertSame( DiceFm::DEFAULT_MAX_ITEMS, DiceFmSettings::get_defaults()['max_items'] ); + $this->assertSame( 25, DiceFmSettings::sanitize( array( 'max_items' => '25' ) )['max_items'] ); + $this->assertSame( 30, DiceFmSettings::sanitize( array( 'horizon_days' => '30' ) )['horizon_days'] ); + + $this->mockDice( 2, DiceFm::PAGE_SIZE ); + $this->assertCount( DiceFm::DEFAULT_MAX_ITEMS, $this->fetch( array() ) ); + } + + public function test_failed_later_page_keeps_earlier_pages(): void { + $this->mockDice( 3, 2, 1, null, 2 ); + + $packets = $this->fetch( array( 'max_items' => 0 ) ); + + $this->assertCount( 2, $packets ); + $this->assertCount( 2, $this->queries ); + } + + private function fetch( array $overrides ): array { + $step = 'dice-pages-' . uniqid(); + return ( new DiceFmHttpTestDouble() )->get_fetch_data( + 1, + array_merge( + array( + 'pipeline_id' => 1, + 'flow_id' => abs( crc32( $step ) ), + 'flow_step_id' => $step, + 'city' => 'London', + 'country' => 'United Kingdom', + ), + $overrides + ), + (string) wp_rand( 10000, 99999 ) + ); + } + + /** + * Mock the Dice partner API. + * + * @param int $pages Total pages the API reports. + * @param int $per_page Events per page. + * @param int $step_days Days between consecutive events (negative = descending). + * @param callable|null $country Country resolver (page, index) => string. + * @param int $fail_page Page that returns HTTP 500 (0 = none). + */ + private function mockDice( int $pages, int $per_page, int $step_days = 1, ?callable $country = null, int $fail_page = 0 ): void { + $run = uniqid(); + add_filter( + 'pre_http_request', + function ( $pre, $args, $url ) use ( $pages, $per_page, $step_days, $country, $fail_page, $run ) { + if ( false === strpos( (string) $url, 'partners-endpoint.dice.fm' ) ) { + return $pre; + } + $query = array(); + parse_str( (string) wp_parse_url( $url, PHP_URL_QUERY ), $query ); + $flat = array(); + $flat['page[size]'] = (string) ( $query['page']['size'] ?? '' ); + $flat['page[number]'] = (string) ( $query['page']['number'] ?? '' ); + $flat['filter'] = $query['filter'] ?? array(); + $this->queries[] = $flat; + $page = (int) $flat['page[number]']; + + if ( $page === $fail_page ) { + return array( + 'headers' => array(), + 'response' => array( + 'code' => 500, + 'message' => 'Server Error', + ), + 'body' => '{}', + ); + } + + $events = array(); + for ( $i = 1; $i <= $per_page && $page <= $pages; $i++ ) { + $ordinal = ( ( $page - 1 ) * $per_page ) + $i; + $offset = $step_days >= 0 ? 1 + ( ( $ordinal - 1 ) * $step_days ) : 1 + ( ( $pages * $per_page ) - $ordinal ); + $events[] = array( + 'id' => "dice-{$run}-{$page}-{$i}", + 'name' => "Dice Show p{$page}-{$i}", + 'date' => gmdate( 'Y-m-d\TH:i:s\Z', time() + ( $offset * DAY_IN_SECONDS ) ), + 'timezone' => 'Europe/London', + 'venue' => 'Dice Test Venue', + 'url' => "https://dice.fm/event/{$run}-{$page}-{$i}", + 'location' => array( + 'city' => 'London', + 'country' => $country ? $country( $page, $i ) : 'United Kingdom', + ), + ); + } + + $links = array( 'self' => $url ); + if ( $page < $pages ) { + $links['next'] = add_query_arg( 'page[number]', $page + 1, 'https://partners-endpoint.dice.fm/api/v2/events' ); + } + + return array( + 'headers' => array( 'content-type' => 'application/json' ), + 'response' => array( + 'code' => 200, + 'message' => 'OK', + ), + 'body' => wp_json_encode( + array( + 'data' => $events, + 'links' => $links, + ) + ), + ); + }, + 10, + 3 + ); + } + + private function logsMatching( string $needle ): array { + return array_values( + array_filter( + $this->logs, + static fn( array $log ): bool => false !== stripos( $log['message'], $needle ) + ) + ); + } +} + +/** Real HTTP pagination with only credentials stubbed. */ +class DiceFmHttpTestDouble extends DiceFm { + + protected function getAuthProvider( string $provider_key ): ?object { + return new class() { + public function get_account(): array { + return array( 'api_key' => 'test-key' ); + } + }; + } +} diff --git a/plugins/data-machine-events/tests/Unit/TicketmasterGeoWindowTest.php b/plugins/data-machine-events/tests/Unit/TicketmasterGeoWindowTest.php new file mode 100644 index 000000000..c23d7fa0f --- /dev/null +++ b/plugins/data-machine-events/tests/Unit/TicketmasterGeoWindowTest.php @@ -0,0 +1,255 @@ + Query args for each mocked request. */ + private array $queries = array(); + + /** @var array Captured logs. */ + private array $logs = array(); + + /** @var array Mock inventory, date ascending. */ + private array $inventory = array(); + + public function setUp(): void { + parent::setUp(); + if ( ! post_type_exists( Event_Post_Type::POST_TYPE ) ) { + Event_Post_Type::register(); + } + if ( ! taxonomy_exists( 'venue' ) ) { + Venue_Taxonomy::register(); + } + if ( ! EventDatesTable::table_exists() ) { + EventDatesTable::create_table(); + } + Agents::create_table(); + BatchItems::create_table(); + Flows::create_table(); + Jobs::create_table(); + Pipelines::create_table(); + ( new ProcessedItems() )->create_table(); + ( new TrackedItems() )->create_table(); + $this->tracked_completion_filter = static fn( array $handlers ): array => TrackedItems::registerClaimCompletionHandler( $handlers ); + add_filter( 'datamachine_item_claim_completion_handlers', $this->tracked_completion_filter ); + set_transient( 'data_machine_events_ticketmaster_classifications', array( 'music' => 'Music' ) ); + add_filter( 'pre_http_request', array( $this, 'mockDiscovery' ), 10, 3 ); + add_action( 'datamachine_log', array( $this, 'captureLog' ), 10, 3 ); + $this->queries = array(); + $this->logs = array(); + $this->inventory = array(); + } + + public function tearDown(): void { + remove_filter( 'pre_http_request', array( $this, 'mockDiscovery' ), 10 ); + remove_action( 'datamachine_log', array( $this, 'captureLog' ), 10 ); + remove_filter( 'datamachine_item_claim_completion_handlers', $this->tracked_completion_filter ); + delete_transient( 'data_machine_events_ticketmaster_classifications' ); + parent::tearDown(); + } + + public function test_under_cap_geo_query_is_unchanged(): void { + $this->seedInventory( 60, 30 ); + + $packets = $this->fetch( 'geo-under-cap' ); + + $this->assertCount( 60, $packets ); + $this->assertCount( 2, $this->queries ); + foreach ( $this->queries as $query ) { + $this->assertSame( '50', $query['size'] ); + $this->assertArrayNotHasKey( 'endDateTime', $query ); + $this->assertArrayHasKey( 'geoPoint', $query ); + } + $this->assertEmpty( $this->logsMatching( 'date windows' ) ); + } + + public function test_over_cap_geo_query_is_split_into_date_windows_and_reaches_every_event(): void { + // 1,200 events, 30 per day: more than the 1,000 deep-paging reach. + $this->seedInventory( 1200, 30 ); + + $packets = $this->fetch( 'geo-over-cap' ); + + $this->assertCount( Ticketmaster::DEFAULT_MAX_ITEMS, $packets ); + $this->assertCount( 1, $this->logsMatching( 'splitting into date windows', 'info' ) ); + $this->assertEmpty( $this->logsMatching( 'pagination cap', 'warning' ) ); + + $summary = $this->logsMatching( 'fan-out summary' ); + $this->assertCount( 1, $summary ); + $this->assertSame( 1200, $summary[0]['context']['eligible_before_bound'] ); + $this->assertSame( 0, $summary[0]['context']['repeated_source_ids'] ); + + // Nearest dates are selected first. + $this->assertSame( $this->inventory[0]['event']['id'], $packets[0]->addTo( array() )[0]['metadata']['source_item_id'] ); + + $page_queries = array_values( array_filter( $this->queries, static fn( array $q ): bool => '50' === $q['size'] ) ); + $windowed = array_values( array_filter( $page_queries, static fn( array $q ): bool => isset( $q['endDateTime'] ) ) ); + $this->assertNotEmpty( $windowed ); + foreach ( $this->queries as $query ) { + $this->assertArrayHasKey( 'geoPoint', $query ); + $this->assertSame( 'date,asc', $query['sort'] ); + } + } + + public function test_window_still_over_cap_at_one_day_logs_truncation(): void { + // Every event lands on the same instant, so no window can split it. + $this->seedInventory( 1010, 1010, 3 ); + + $packets = $this->fetch( 'geo-dense-day' ); + + $this->assertCount( Ticketmaster::DEFAULT_MAX_ITEMS, $packets ); + $warnings = $this->logsMatching( 'pagination cap', 'warning' ); + $this->assertCount( 1, $warnings ); + $this->assertNotSame( '', $warnings[0]['context']['end_date_time'] ); + $this->assertSame( 1010, $warnings[0]['context']['total_elements'] ); + $summary = $this->logsMatching( 'fan-out summary' ); + $this->assertSame( 1000, $summary[0]['context']['eligible_before_bound'] ); + } + + public function captureLog( string $level, string $message, array $context = array() ): void { + $this->logs[] = array( + 'level' => $level, + 'message' => $message, + 'context' => $context, + ); + } + + public function mockDiscovery( $pre, $args, $url ) { + if ( false === strpos( (string) $url, 'events.json' ) ) { + return $pre; + } + $query = array(); + parse_str( (string) wp_parse_url( $url, PHP_URL_QUERY ), $query ); + $this->queries[] = $query; + + $start = isset( $query['startDateTime'] ) ? strtotime( $query['startDateTime'] ) : 0; + $end = isset( $query['endDateTime'] ) ? strtotime( $query['endDateTime'] ) : PHP_INT_MAX; + $matches = array_values( + array_filter( + $this->inventory, + static fn( array $row ): bool => $row['ts'] >= $start && $row['ts'] <= $end + ) + ); + $size = max( 1, (int) $query['size'] ); + $page = (int) $query['page']; + $events = array_column( array_slice( $matches, $page * $size, $size ), 'event' ); + + return array( + 'headers' => array( 'content-type' => 'application/json' ), + 'response' => array( + 'code' => 200, + 'message' => 'OK', + ), + 'body' => wp_json_encode( + array( + '_embedded' => array( 'events' => $events ), + 'page' => array( + 'number' => $page, + 'size' => $size, + 'totalPages' => (int) ceil( count( $matches ) / $size ), + 'totalElements' => count( $matches ), + ), + ) + ), + ); + } + + private function fetch( string $step ): array { + return ( new TicketmasterWindowHttpTestDouble() )->get_fetch_data( + 1, + array( + 'pipeline_id' => 1, + 'flow_id' => abs( crc32( $step ) ), + 'flow_step_id' => $step . '-' . uniqid(), + 'classification_type' => 'music', + 'location' => '51.5074,-0.1278', + 'radius' => '15', + 'max_items' => Ticketmaster::DEFAULT_MAX_ITEMS, + ), + (string) wp_rand( 10000, 99999 ) + ); + } + + /** + * Seed the mock Discovery inventory. + * + * @param int $count Number of events. + * @param int $per_day Events per calendar day. + * @param int $first_day Day offset of the first event. + */ + private function seedInventory( int $count, int $per_day, int $first_day = 0 ): void { + $prefix = uniqid(); + $base = time() + ( 2 * HOUR_IN_SECONDS ) + ( $first_day * DAY_IN_SECONDS ); + for ( $i = 0; $i < $count; $i++ ) { + $ts = $base + ( intdiv( $i, $per_day ) * DAY_IN_SECONDS ); + $this->inventory[] = array( + 'ts' => $ts, + 'event' => array( + 'id' => "TMW-{$prefix}-{$i}", + 'name' => "Window Concert {$i}", + 'url' => "https://www.ticketmaster.com/event/TMW-{$prefix}-{$i}", + 'dates' => array( + 'status' => array( 'code' => 'onsale' ), + 'start' => array( + 'localDate' => gmdate( 'Y-m-d', $ts ), + 'localTime' => gmdate( 'H:i:s', $ts ), + 'dateTime' => gmdate( 'Y-m-d\TH:i:s\Z', $ts ), + ), + ), + '_embedded' => array( + 'venues' => array( + array( + 'name' => 'Window Hall', + 'timezone' => 'UTC', + 'address' => array( 'line1' => '1 Window Way' ), + 'city' => array( 'name' => 'London' ), + 'country' => array( 'countryCode' => 'GB' ), + ), + ), + ), + ), + ); + } + } + + private function logsMatching( string $needle, string $level = '' ): array { + return array_values( + array_filter( + $this->logs, + static fn( array $log ): bool => false !== stripos( $log['message'], $needle ) && ( '' === $level || $level === $log['level'] ) + ) + ); + } +} + +/** Real HTTP pagination with only credentials stubbed. */ +class TicketmasterWindowHttpTestDouble extends Ticketmaster { + + protected function getAuthProvider( string $provider_key ): ?object { + return new class() { + public function get_account(): array { + return array( 'api_key' => 'test-key' ); + } + }; + } +} diff --git a/plugins/data-machine-events/tests/Unit/TicketmasterHandlerTest.php b/plugins/data-machine-events/tests/Unit/TicketmasterHandlerTest.php index 78152ca2b..200ddc397 100644 --- a/plugins/data-machine-events/tests/Unit/TicketmasterHandlerTest.php +++ b/plugins/data-machine-events/tests/Unit/TicketmasterHandlerTest.php @@ -1444,8 +1444,9 @@ public function test_query_truncation_is_visible_and_geo_pagination_is_unchanged public static function truncatedQueryModes(): array { return array( + // Geo mode splits over-cap queries into date windows instead (#4108); + // see TicketmasterGeoWindowTest. 'artist' => array( true ), - 'geo' => array( false ), ); }