Merge "Add attributes parameter to ShowSearchHitTitle"
[lhc/web/wiklou.git] / includes / deferred / SiteStatsUpdate.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20 use MediaWiki\MediaWikiServices;
21 use Wikimedia\Assert\Assert;
22 use Wikimedia\Rdbms\IDatabase;
23
24 /**
25 * Class for handling updates to the site_stats table
26 */
27 class SiteStatsUpdate implements DeferrableUpdate, MergeableUpdate {
28 /** @var int */
29 protected $edits = 0;
30 /** @var int */
31 protected $pages = 0;
32 /** @var int */
33 protected $articles = 0;
34 /** @var int */
35 protected $users = 0;
36 /** @var int */
37 protected $images = 0;
38
39 private static $counters = [ 'edits', 'pages', 'articles', 'users', 'images' ];
40
41 // @todo deprecate this constructor
42 function __construct( $views, $edits, $good, $pages = 0, $users = 0 ) {
43 $this->edits = $edits;
44 $this->articles = $good;
45 $this->pages = $pages;
46 $this->users = $users;
47 }
48
49 public function merge( MergeableUpdate $update ) {
50 /** @var SiteStatsUpdate $update */
51 Assert::parameterType( __CLASS__, $update, '$update' );
52
53 foreach ( self::$counters as $field ) {
54 $this->$field += $update->$field;
55 }
56 }
57
58 /**
59 * @param array $deltas
60 * @return SiteStatsUpdate
61 */
62 public static function factory( array $deltas ) {
63 $update = new self( 0, 0, 0 );
64
65 foreach ( self::$counters as $field ) {
66 if ( isset( $deltas[$field] ) && $deltas[$field] ) {
67 $update->$field = $deltas[$field];
68 }
69 }
70
71 return $update;
72 }
73
74 public function doUpdate() {
75 global $wgSiteStatsAsyncFactor;
76
77 $this->doUpdateContextStats();
78
79 $rate = $wgSiteStatsAsyncFactor; // convenience
80 // If set to do so, only do actual DB updates 1 every $rate times.
81 // The other times, just update "pending delta" values in memcached.
82 if ( $rate && ( $rate < 0 || mt_rand( 0, $rate - 1 ) != 0 ) ) {
83 $this->doUpdatePendingDeltas();
84 } else {
85 // Need a separate transaction because this a global lock
86 DeferredUpdates::addCallableUpdate( [ $this, 'tryDBUpdateInternal' ] );
87 }
88 }
89
90 /**
91 * Do not call this outside of SiteStatsUpdate
92 */
93 public function tryDBUpdateInternal() {
94 global $wgSiteStatsAsyncFactor;
95
96 $dbw = wfGetDB( DB_MASTER );
97 $lockKey = wfWikiID() . ':site_stats'; // prepend wiki ID
98 $pd = [];
99 if ( $wgSiteStatsAsyncFactor ) {
100 // Lock the table so we don't have double DB/memcached updates
101 if ( !$dbw->lockIsFree( $lockKey, __METHOD__ )
102 || !$dbw->lock( $lockKey, __METHOD__, 1 ) // 1 sec timeout
103 ) {
104 $this->doUpdatePendingDeltas();
105
106 return;
107 }
108 $pd = $this->getPendingDeltas();
109 // Piggy-back the async deltas onto those of this stats update....
110 $this->edits += ( $pd['ss_total_edits']['+'] - $pd['ss_total_edits']['-'] );
111 $this->articles += ( $pd['ss_good_articles']['+'] - $pd['ss_good_articles']['-'] );
112 $this->pages += ( $pd['ss_total_pages']['+'] - $pd['ss_total_pages']['-'] );
113 $this->users += ( $pd['ss_users']['+'] - $pd['ss_users']['-'] );
114 $this->images += ( $pd['ss_images']['+'] - $pd['ss_images']['-'] );
115 }
116
117 // Build up an SQL query of deltas and apply them...
118 $updates = '';
119 $this->appendUpdate( $updates, 'ss_total_edits', $this->edits );
120 $this->appendUpdate( $updates, 'ss_good_articles', $this->articles );
121 $this->appendUpdate( $updates, 'ss_total_pages', $this->pages );
122 $this->appendUpdate( $updates, 'ss_users', $this->users );
123 $this->appendUpdate( $updates, 'ss_images', $this->images );
124 if ( $updates != '' ) {
125 $dbw->update( 'site_stats', [ $updates ], [], __METHOD__ );
126 }
127
128 if ( $wgSiteStatsAsyncFactor ) {
129 // Decrement the async deltas now that we applied them
130 $this->removePendingDeltas( $pd );
131 // Commit the updates and unlock the table
132 $dbw->unlock( $lockKey, __METHOD__ );
133 }
134
135 // Invalid cache used by parser functions
136 SiteStats::unload();
137 }
138
139 /**
140 * @param IDatabase $dbw
141 * @return bool|mixed
142 */
143 public static function cacheUpdate( $dbw ) {
144 global $wgActiveUserDays;
145 $dbr = wfGetDB( DB_REPLICA, 'vslow' );
146 # Get non-bot users than did some recent action other than making accounts.
147 # If account creation is included, the number gets inflated ~20+ fold on enwiki.
148 $activeUsers = $dbr->selectField(
149 'recentchanges',
150 'COUNT( DISTINCT rc_user_text )',
151 [
152 'rc_type != ' . $dbr->addQuotes( RC_EXTERNAL ), // Exclude external (Wikidata)
153 'rc_user != 0',
154 'rc_bot' => 0,
155 'rc_log_type != ' . $dbr->addQuotes( 'newusers' ) . ' OR rc_log_type IS NULL',
156 'rc_timestamp >= ' . $dbr->addQuotes( $dbr->timestamp( wfTimestamp( TS_UNIX )
157 - $wgActiveUserDays * 24 * 3600 ) ),
158 ],
159 __METHOD__
160 );
161 $dbw->update(
162 'site_stats',
163 [ 'ss_active_users' => intval( $activeUsers ) ],
164 [ 'ss_row_id' => 1 ],
165 __METHOD__
166 );
167
168 // Invalid cache used by parser functions
169 SiteStats::unload();
170
171 return $activeUsers;
172 }
173
174 protected function doUpdateContextStats() {
175 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
176 foreach ( [ 'edits', 'articles', 'pages', 'users', 'images' ] as $type ) {
177 $delta = $this->$type;
178 if ( $delta !== 0 ) {
179 $stats->updateCount( "site.$type", $delta );
180 }
181 }
182 }
183
184 protected function doUpdatePendingDeltas() {
185 $this->adjustPending( 'ss_total_edits', $this->edits );
186 $this->adjustPending( 'ss_good_articles', $this->articles );
187 $this->adjustPending( 'ss_total_pages', $this->pages );
188 $this->adjustPending( 'ss_users', $this->users );
189 $this->adjustPending( 'ss_images', $this->images );
190 }
191
192 /**
193 * @param string &$sql
194 * @param string $field
195 * @param int $delta
196 */
197 protected function appendUpdate( &$sql, $field, $delta ) {
198 if ( $delta ) {
199 if ( $sql ) {
200 $sql .= ',';
201 }
202 if ( $delta < 0 ) {
203 $sql .= "$field=$field-" . abs( $delta );
204 } else {
205 $sql .= "$field=$field+" . abs( $delta );
206 }
207 }
208 }
209
210 /**
211 * @param BagOStuff $cache
212 * @param string $type
213 * @param string $sign ('+' or '-')
214 * @return string
215 */
216 private function getTypeCacheKey( BagOStuff $cache, $type, $sign ) {
217 return $cache->makeKey( 'sitestatsupdate', 'pendingdelta', $type, $sign );
218 }
219
220 /**
221 * Adjust the pending deltas for a stat type.
222 * Each stat type has two pending counters, one for increments and decrements
223 * @param string $type
224 * @param int $delta Delta (positive or negative)
225 */
226 protected function adjustPending( $type, $delta ) {
227 $cache = MediaWikiServices::getInstance()->getMainObjectStash();
228 if ( $delta < 0 ) { // decrement
229 $key = $this->getTypeCacheKey( $cache, $type, '-' );
230 } else { // increment
231 $key = $this->getTypeCacheKey( $cache, $type, '+' );
232 }
233
234 $magnitude = abs( $delta );
235 $cache->incrWithInit( $key, 0, $magnitude, $magnitude );
236 }
237
238 /**
239 * Get pending delta counters for each stat type
240 * @return array Positive and negative deltas for each type
241 */
242 protected function getPendingDeltas() {
243 $cache = MediaWikiServices::getInstance()->getMainObjectStash();
244
245 $pending = [];
246 foreach ( [ 'ss_total_edits',
247 'ss_good_articles', 'ss_total_pages', 'ss_users', 'ss_images' ] as $type
248 ) {
249 // Get pending increments and pending decrements
250 $flg = BagOStuff::READ_LATEST;
251 $pending[$type]['+'] = (int)$cache->get( $this->getTypeCacheKey( $cache, $type, '+' ), $flg );
252 $pending[$type]['-'] = (int)$cache->get( $this->getTypeCacheKey( $cache, $type, '-' ), $flg );
253 }
254
255 return $pending;
256 }
257
258 /**
259 * Reduce pending delta counters after updates have been applied
260 * @param array $pd Result of getPendingDeltas(), used for DB update
261 */
262 protected function removePendingDeltas( array $pd ) {
263 $cache = MediaWikiServices::getInstance()->getMainObjectStash();
264
265 foreach ( $pd as $type => $deltas ) {
266 foreach ( $deltas as $sign => $magnitude ) {
267 // Lower the pending counter now that we applied these changes
268 $cache->decr( $this->getTypeCacheKey( $cache, $type, $sign ), $magnitude );
269 }
270 }
271 }
272 }