8c38d8b0ca46f18b4e40da665ec6db6cc51df88d
[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_user != 0',
153 'rc_bot' => 0,
154 'rc_log_type != ' . $dbr->addQuotes( 'newusers' ) . ' OR rc_log_type IS NULL',
155 'rc_timestamp >= ' . $dbr->addQuotes( $dbr->timestamp( wfTimestamp( TS_UNIX )
156 - $wgActiveUserDays * 24 * 3600 ) ),
157 ],
158 __METHOD__
159 );
160 $dbw->update(
161 'site_stats',
162 [ 'ss_active_users' => intval( $activeUsers ) ],
163 [ 'ss_row_id' => 1 ],
164 __METHOD__
165 );
166
167 // Invalid cache used by parser functions
168 SiteStats::unload();
169
170 return $activeUsers;
171 }
172
173 protected function doUpdateContextStats() {
174 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
175 foreach ( [ 'edits', 'articles', 'pages', 'users', 'images' ] as $type ) {
176 $delta = $this->$type;
177 if ( $delta !== 0 ) {
178 $stats->updateCount( "site.$type", $delta );
179 }
180 }
181 }
182
183 protected function doUpdatePendingDeltas() {
184 $this->adjustPending( 'ss_total_edits', $this->edits );
185 $this->adjustPending( 'ss_good_articles', $this->articles );
186 $this->adjustPending( 'ss_total_pages', $this->pages );
187 $this->adjustPending( 'ss_users', $this->users );
188 $this->adjustPending( 'ss_images', $this->images );
189 }
190
191 /**
192 * @param string $sql
193 * @param string $field
194 * @param int $delta
195 */
196 protected function appendUpdate( &$sql, $field, $delta ) {
197 if ( $delta ) {
198 if ( $sql ) {
199 $sql .= ',';
200 }
201 if ( $delta < 0 ) {
202 $sql .= "$field=$field-" . abs( $delta );
203 } else {
204 $sql .= "$field=$field+" . abs( $delta );
205 }
206 }
207 }
208
209 /**
210 * @param BagOStuff $cache
211 * @param string $type
212 * @param string $sign ('+' or '-')
213 * @return string
214 */
215 private function getTypeCacheKey( BagOStuff $cache, $type, $sign ) {
216 return $cache->makeKey( 'sitestatsupdate', 'pendingdelta', $type, $sign );
217 }
218
219 /**
220 * Adjust the pending deltas for a stat type.
221 * Each stat type has two pending counters, one for increments and decrements
222 * @param string $type
223 * @param int $delta Delta (positive or negative)
224 */
225 protected function adjustPending( $type, $delta ) {
226 $cache = MediaWikiServices::getInstance()->getMainObjectStash();
227 if ( $delta < 0 ) { // decrement
228 $key = $this->getTypeCacheKey( $cache, $type, '-' );
229 } else { // increment
230 $key = $this->getTypeCacheKey( $cache, $type, '+' );
231 }
232
233 $magnitude = abs( $delta );
234 $cache->incrWithInit( $key, 0, $magnitude, $magnitude );
235 }
236
237 /**
238 * Get pending delta counters for each stat type
239 * @return array Positive and negative deltas for each type
240 */
241 protected function getPendingDeltas() {
242 $cache = MediaWikiServices::getInstance()->getMainObjectStash();
243
244 $pending = [];
245 foreach ( [ 'ss_total_edits',
246 'ss_good_articles', 'ss_total_pages', 'ss_users', 'ss_images' ] as $type
247 ) {
248 // Get pending increments and pending decrements
249 $flg = BagOStuff::READ_LATEST;
250 $pending[$type]['+'] = (int)$cache->get( $this->getTypeCacheKey( $cache, $type, '+' ), $flg );
251 $pending[$type]['-'] = (int)$cache->get( $this->getTypeCacheKey( $cache, $type, '-' ), $flg );
252 }
253
254 return $pending;
255 }
256
257 /**
258 * Reduce pending delta counters after updates have been applied
259 * @param array $pd Result of getPendingDeltas(), used for DB update
260 */
261 protected function removePendingDeltas( array $pd ) {
262 $cache = MediaWikiServices::getInstance()->getMainObjectStash();
263
264 foreach ( $pd as $type => $deltas ) {
265 foreach ( $deltas as $sign => $magnitude ) {
266 // Lower the pending counter now that we applied these changes
267 $cache->decr( $this->getTypeCacheKey( $cache, $type, $sign ), $magnitude );
268 }
269 }
270 }
271 }