Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
98.92% covered (success)
98.92%
184 / 186
66.67% covered (warning)
66.67%
2 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
ChoiceDataProvider
98.92% covered (success)
98.92%
184 / 186
66.67% covered (warning)
66.67%
2 / 3
18
0.00% covered (danger)
0.00%
0 / 1
 invalidateCache
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 getChoices
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
1 / 1
2
 fetchChoices
98.76% covered (success)
98.76%
159 / 161
0.00% covered (danger)
0.00%
0 / 1
15
1<?php
2
3use MediaWiki\MediaWikiServices;
4use Wikimedia\ObjectCache\WANObjectCache;
5use Wikimedia\Rdbms\IReadableDatabase;
6
7/**
8 * Provides a set of campaign and banner choices based on allocations for a
9 * given project and language combination.
10 */
11class ChoiceDataProvider {
12
13    /** @var string Common prefix for choice data cache keys */
14    private const CACHE_KEY_NAMESPACE = 'CentralNoticeChoiceData';
15
16    /** @var int Time-to-live for choice data cache entries */
17    private const CACHE_TTL = WANObjectCache::TTL_HOUR;
18
19    /** @var int How long to use a stale value while one thread recalculates */
20    private const CACHE_TSE = 30 * WANObjectCache::TTL_SECOND;
21
22    /**
23     * Invalidate the shared global cache.
24     * @return bool
25     */
26    public static function invalidateCache() {
27        $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
28        return $cache->touchCheckKey(
29            $cache->makeGlobalKey( self::CACHE_KEY_NAMESPACE, 'check' ) );
30    }
31
32    /**
33     * Get a data structure with the allocation choices.
34     *
35     * @param string $project The project to get choices for
36     * @param string $language The language to get choices for
37     * @return array A structure of arrays. The outer array contains associative
38     *   arrays that represent campaigns. One campaign property is 'banners',
39     *   which has as its value an array of associative arrays that represent
40     *   banners. Note that only some properties of campaigns and banners
41     *   are provided.
42     */
43    public static function getChoices( $project, $language ) {
44        $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
45
46        $dataKey = $cache->makeGlobalKey( self::CACHE_KEY_NAMESPACE, $project, $language );
47        $checkKey = $cache->makeGlobalKey( self::CACHE_KEY_NAMESPACE, 'check' );
48
49        $choices = $cache->getWithSetCallback(
50            $dataKey,
51            self::CACHE_TTL,
52            function ()
53                use ( $project, $language ) {
54                $dbr = CNDatabase::getReplicaDb();
55                return self::fetchChoices( $project, $language, $dbr );
56            },
57            [
58                'checkKeys' => [ $checkKey ],
59                // While requests for this data are heavily cached by
60                // Varnish for all users, we still allow a stale value
61                // to be used for 30 seconds as invalidation is frequent
62                // and calculation involves many DB queries.
63                'lockTSE' => self::CACHE_TSE,
64                // Update the cache at most once per request
65                'pcTTL' => $cache::TTL_PROC_LONG,
66            ]
67        );
68
69        // Filter out campaigns that have ended since we last queried the
70        // database or which have not started yet. array_values re-orders numeric
71        // keys, in case elements were removed.
72        $now = time();
73        return array_values( array_filter(
74            $choices,
75            static fn ( array $choice ) => $choice['end'] >= $now && $choice['start'] <= $now
76        ) );
77    }
78
79    /**
80     * @param string $project
81     * @param string $language
82     * @param IReadableDatabase $dbr
83     *
84     * @return array
85     */
86    private static function fetchChoices( $project, $language,
87        IReadableDatabase $dbr
88    ) {
89        // For speed, we'll do our own queries instead of using methods in
90        // Campaign and Banner.
91
92        // Set up conditions
93        // Choice data will be cached for up to an hour, so we want to include
94        // campaigns that will start during that interval.
95        $start = $dbr->timestamp( time() + self::CACHE_TTL );
96        $end = $dbr->timestamp();
97        $conds = [
98            $dbr->expr( 'notices.not_start', '<=', $start ),
99            $dbr->expr( 'notices.not_end', '>=', $end ),
100            'notices.not_enabled' => 1,
101            'notices.not_archived' => 0,
102            'notice_projects.np_project' => $project,
103            'notice_languages.nl_language' => $language
104        ];
105
106        // Query campaigns and banners at once
107        $dbRows = $dbr->newSelectQueryBuilder()
108            ->select( [
109                'notices.not_id',
110                'notices.not_name',
111                'notices.not_start',
112                'notices.not_end',
113                'notices.not_preferred',
114                'notices.not_throttle',
115                'notices.not_geo',
116                'notices.not_buckets',
117                'notices.not_type',
118                'assignments.tmp_weight',
119                'assignments.asn_bucket',
120                'templates.tmp_id',
121                'templates.tmp_name',
122                'templates.tmp_display_anon',
123                'templates.tmp_display_account',
124                'templates.tmp_category'
125            ] );
126        // Could be null if database is disabled e.g. during tests
127        if ( $dbRows === null ) {
128            return [];
129        }
130        $dbRows = $dbRows->from( 'cn_notices', 'notices' )
131            ->join(    'cn_assignments', 'assignments', 'notices.not_id = assignments.not_id' )
132            ->join(    'cn_templates', 'templates', 'assignments.tmp_id = templates.tmp_id' )
133            ->join(    'cn_notice_projects', 'notice_projects', 'notices.not_id = notice_projects.np_notice_id' )
134            ->join(    'cn_notice_languages', 'notice_languages', 'notices.not_id = notice_languages.nl_notice_id' )
135            ->where( $conds )
136            ->caller( __METHOD__ )
137            ->fetchResultSet();
138
139        // Pare it down into a nicer data structure and prepare the next queries.
140        // We'll create a structure with keys that are useful for piecing the
141        // data together. But before returning it, we'll change associative
142        // arrays to indexed ones at levels where the keys are not needed by the
143        // client.
144        $choices = [];
145        $bannerIds = [];
146        $assignmentKeysByBannerIdAndCampaignId = [];
147
148        foreach ( $dbRows as $dbRow ) {
149            $campaignId = $dbRow->not_id;
150            $campaignName = $dbRow->not_name;
151            $bannerId = $dbRow->tmp_id;
152            $bannerName = $dbRow->tmp_name;
153            $bucket = $dbRow->asn_bucket;
154
155            // FIXME Temporary hack to substitute the magic words {{{campaign}}}
156            // and {{{banner}}} in banner categories. (These are the magic
157            // words mentioned in the CN Admin UI.)
158            $category = $dbRow->tmp_category;
159            $category = str_replace( '{{{campaign}}}', $campaignName, $category );
160            $category = str_replace( '{{{banner}}}', $bannerName, $category );
161            $category = Banner::sanitizeRenderedCategory( $category );
162
163            // The first time we see any campaign, create the corresponding
164            // outer K/V entry. The campaign-specific properties should be
165            // repeated on every row for any campaign. Note that these
166            // keys don't make it into data structure we return.
167            if ( !isset( $choices[$campaignId] ) ) {
168                $choices[$campaignId] = [
169                    'name' => $campaignName,
170                    'start' => intval( wfTimestamp( TS_UNIX, $dbRow->not_start ) ),
171                    'end' => intval( wfTimestamp( TS_UNIX, $dbRow->not_end ) ),
172                    'preferred' => intval( $dbRow->not_preferred ),
173                    'throttle' => intval( $dbRow->not_throttle ),
174                    'bucket_count' => intval( $dbRow->not_buckets ),
175                    'geotargeted' => (bool)$dbRow->not_geo,
176                    'type' => $dbRow->not_type,
177                    'banners' => []
178                ];
179            }
180
181            // A temporary assignment key so we can get back to this part of the
182            // data structure quickly and add in devices.
183            $assignmentKey = $bannerId . ':' . $bucket;
184
185            $choices[$campaignId]['banners'][$assignmentKey] = [
186                'name' => $bannerName,
187                'bucket' => intval( $bucket ),
188                'weight' => intval( $dbRow->tmp_weight ),
189                'category' => $category,
190                'display_anon' => (bool)$dbRow->tmp_display_anon,
191                'display_account' => (bool)$dbRow->tmp_display_account,
192                // To be filled by the last query
193                'devices' => []
194            ];
195
196            $bannerIds[] = $bannerId;
197
198            // Add to the index so we can get back here.
199            // Note that PHP creates arrays here as needed.
200            $assignmentKeysByBannerIdAndCampaignId[$bannerId][$campaignId][] =
201                $assignmentKey;
202        }
203
204        // If there's nothing, return the empty array now
205        if ( count( $choices ) === 0 ) {
206            return $choices;
207        }
208
209        // Fetch countries.
210        // We have to eliminate notices that are not geotargeted, since they
211        // may have residual data in the cn_notice_countries table.
212        $dbRows = $dbr->newSelectQueryBuilder()
213            ->select( [
214                'notices.not_id',
215                'notice_countries.nc_country'
216            ] )
217            ->from( 'cn_notices', 'notices' )
218            ->join( 'cn_notice_countries', 'notice_countries', 'notices.not_id = notice_countries.nc_notice_id' )
219            ->where( [
220                'notices.not_geo' => 1,
221                'notices.not_id' => array_keys( $choices )
222            ] )
223            ->caller( __METHOD__ )
224            ->fetchResultSet();
225
226        // Add countries to our data structure.
227        // Note that PHP creates an empty array for countries as needed.
228        foreach ( $dbRows as $dbRow ) {
229            $choices[$dbRow->not_id]['countries'][] = $dbRow->nc_country;
230        }
231
232        // Fetch regions.
233        // We have to eliminate notices that are not geotargeted, since they
234        // may have residual data in the cn_notice_regions table.
235        $dbRows = $dbr->newSelectQueryBuilder()
236            ->select( [
237                'notices.not_id',
238                'notice_regions.nr_region'
239            ] )
240            ->from( 'cn_notices', 'notices' )
241            ->join( 'cn_notice_regions', 'notice_regions', 'notices.not_id = notice_regions.nr_notice_id' )
242            ->where( [
243                'notices.not_geo' => 1,
244                'notices.not_id' => array_keys( $choices )
245            ] )
246            ->caller( __METHOD__ )
247            ->fetchResultSet();
248
249        // Add regions to our data structure.
250        // Note that PHP creates an empty array for regions as needed.
251        foreach ( $dbRows as $dbRow ) {
252            $choices[$dbRow->not_id]['regions'][] = $dbRow->nr_region;
253        }
254
255        // FIXME: looks like this is only sorting the last banner's list!
256        // @phan-suppress-next-line PhanPossiblyUndeclaredVariable
257        if ( isset( $choices[$dbRow->not_id]['countries'] ) ) {
258            // @phan-suppress-next-line PhanPossiblyUndeclaredVariable
259            sort( $choices[$dbRow->not_id]['countries'] );
260        }
261
262        // Add campaign-associated mixins to the data structure
263        $mixins = Campaign::getCompactCampaignMixins(
264            array_map( static fn ( $campaignInfo ) => $campaignInfo['name'], $choices )
265        );
266        foreach ( $choices as &$campaignInfo ) {
267            // Get info for enabled mixins for this campaign
268            $campaignInfo['mixins'] = $mixins[$campaignInfo['name']];
269        }
270
271        // Fetch the devices
272        $dbRows = $dbr->newSelectQueryBuilder()
273            ->select( [
274                'template_devices.tmp_id',
275                'known_devices.dev_name'
276            ] )
277            ->from( 'cn_template_devices', 'template_devices' )
278            ->join( 'cn_known_devices', 'known_devices', 'template_devices.dev_id = known_devices.dev_id' )
279            ->where( [
280                'template_devices.tmp_id' => $bannerIds
281            ] )
282            ->caller( __METHOD__ )
283            ->fetchResultSet();
284
285        // Add devices to the data structure.
286        foreach ( $dbRows as $dbRow ) {
287            $bannerId = $dbRow->tmp_id;
288
289            // Traverse the data structure to add in devices
290
291            $assignmentKeysByCampaignId =
292                $assignmentKeysByBannerIdAndCampaignId[$bannerId];
293
294            foreach ( $assignmentKeysByCampaignId
295                as $campaignId => $assignmentKeys
296            ) {
297                foreach ( $assignmentKeys as $assignmentKey ) {
298                    $choices[$campaignId]['banners'][$assignmentKey]['devices'][] =
299                        $dbRow->dev_name;
300                }
301
302                // Ensure consistent ordering (see comment below)
303                // FIXME: only sorting list for last assignmentKey?
304                // @phan-suppress-next-line PhanTypeArraySuspiciousNullable,PhanPossiblyUndeclaredVariable
305                sort( $choices[$campaignId]['banners'][$assignmentKey]['devices'] );
306            }
307        }
308
309        // Make arrays that are associative into plain indexed ones, since the
310        // keys aren't used by the clients.
311        // Also make very sure we don't have duplicate devices or countries.
312        // Finally, ensure consistent ordering, since it's needed for
313        // CNChoiceDataResourceLoaderModule for consistent RL module hashes.
314
315        $choices = array_values( $choices );
316
317        $uniqueDevFn = static function ( $b ) {
318            $b['devices'] = array_unique( $b['devices'] );
319            return $b;
320        };
321
322        $compareNames = static function ( $a, $b ) {
323            if ( $a['name'] == $b['name'] ) {
324                return 0;
325            }
326            return ( $a['name'] < $b['name'] ) ? -1 : 1;
327        };
328
329        $fixCampaignPropsFn = static function ( $c ) use ( $uniqueDevFn, $compareNames ) {
330            $c['banners'] = array_map( $uniqueDevFn, array_values( $c['banners'] ) );
331            usort( $c['banners'], $compareNames );
332
333            if ( $c['geotargeted'] ) {
334                $c['countries'] = array_unique( $c['countries'] ?? [] );
335                sort( $c['countries'] );
336                $c['regions'] = array_unique( $c['regions'] ?? [] );
337                sort( $c['regions'] );
338            }
339
340            return $c;
341        };
342
343        $choices = array_map( $fixCampaignPropsFn, $choices );
344        usort( $choices, $compareNames );
345
346        return $choices;
347    }
348}