Merge "Title: Refactor JS/CSS page handling to be more sane"
[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 BagOStuff */
29 protected $stash;
30 /** @var int */
31 protected $edits = 0;
32 /** @var int */
33 protected $pages = 0;
34 /** @var int */
35 protected $articles = 0;
36 /** @var int */
37 protected $users = 0;
38 /** @var int */
39 protected $images = 0;
40
41 private static $counters = [ 'edits', 'pages', 'articles', 'users', 'images' ];
42
43 // @todo deprecate this constructor
44 function __construct( $views, $edits, $good, $pages = 0, $users = 0 ) {
45 $this->edits = $edits;
46 $this->articles = $good;
47 $this->pages = $pages;
48 $this->users = $users;
49
50 $this->stash = MediaWikiServices::getInstance()->getMainObjectStash();
51 }
52
53 public function merge( MergeableUpdate $update ) {
54 /** @var SiteStatsUpdate $update */
55 Assert::parameterType( __CLASS__, $update, '$update' );
56
57 foreach ( self::$counters as $field ) {
58 $this->$field += $update->$field;
59 }
60 }
61
62 /**
63 * @param array $deltas
64 * @return SiteStatsUpdate
65 */
66 public static function factory( array $deltas ) {
67 $update = new self( 0, 0, 0 );
68
69 foreach ( self::$counters as $field ) {
70 if ( isset( $deltas[$field] ) && $deltas[$field] ) {
71 $update->$field = $deltas[$field];
72 }
73 }
74
75 return $update;
76 }
77
78 public function doUpdate() {
79 $this->doUpdateContextStats();
80
81 $rate = MediaWikiServices::getInstance()->getMainConfig()->get( 'SiteStatsAsyncFactor' );
82 // If set to do so, only do actual DB updates 1 every $rate times.
83 // The other times, just update "pending delta" values in memcached.
84 if ( $rate && ( $rate < 0 || mt_rand( 0, $rate - 1 ) != 0 ) ) {
85 $this->doUpdatePendingDeltas();
86 } else {
87 // Need a separate transaction because this a global lock
88 DeferredUpdates::addCallableUpdate( [ $this, 'tryDBUpdateInternal' ] );
89 }
90 }
91
92 /**
93 * Do not call this outside of SiteStatsUpdate
94 */
95 public function tryDBUpdateInternal() {
96 $services = MediaWikiServices::getInstance();
97 $config = $services->getMainConfig();
98
99 $dbw = $services->getDBLoadBalancer()->getConnection( DB_MASTER );
100 $lockKey = $dbw->getDomainID() . ':site_stats'; // prepend wiki ID
101 $pd = [];
102 if ( $config->get( 'SiteStatsAsyncFactor' ) ) {
103 // Lock the table so we don't have double DB/memcached updates
104 if ( !$dbw->lock( $lockKey, __METHOD__, 0 ) ) {
105 $this->doUpdatePendingDeltas();
106
107 return;
108 }
109 $pd = $this->getPendingDeltas();
110 // Piggy-back the async deltas onto those of this stats update....
111 $this->edits += ( $pd['ss_total_edits']['+'] - $pd['ss_total_edits']['-'] );
112 $this->articles += ( $pd['ss_good_articles']['+'] - $pd['ss_good_articles']['-'] );
113 $this->pages += ( $pd['ss_total_pages']['+'] - $pd['ss_total_pages']['-'] );
114 $this->users += ( $pd['ss_users']['+'] - $pd['ss_users']['-'] );
115 $this->images += ( $pd['ss_images']['+'] - $pd['ss_images']['-'] );
116 }
117
118 // Build up an SQL query of deltas and apply them...
119 $updates = '';
120 $this->appendUpdate( $updates, 'ss_total_edits', $this->edits );
121 $this->appendUpdate( $updates, 'ss_good_articles', $this->articles );
122 $this->appendUpdate( $updates, 'ss_total_pages', $this->pages );
123 $this->appendUpdate( $updates, 'ss_users', $this->users );
124 $this->appendUpdate( $updates, 'ss_images', $this->images );
125 if ( $updates != '' ) {
126 $dbw->update( 'site_stats', [ $updates ], [], __METHOD__ );
127 }
128
129 if ( $config->get( 'SiteStatsAsyncFactor' ) ) {
130 // Decrement the async deltas now that we applied them
131 $this->removePendingDeltas( $pd );
132 // Commit the updates and unlock the table
133 $dbw->unlock( $lockKey, __METHOD__ );
134 }
135
136 // Invalid cache used by parser functions
137 SiteStats::unload();
138 }
139
140 /**
141 * @param IDatabase $dbw
142 * @return bool|mixed
143 */
144 public static function cacheUpdate( IDatabase $dbw ) {
145 $services = MediaWikiServices::getInstance();
146 $config = $services->getMainConfig();
147
148 $dbr = $services->getDBLoadBalancer()->getConnection( DB_REPLICA, 'vslow' );
149 # Get non-bot users than did some recent action other than making accounts.
150 # If account creation is included, the number gets inflated ~20+ fold on enwiki.
151 $activeUsers = $dbr->selectField(
152 'recentchanges',
153 'COUNT( DISTINCT rc_user_text )',
154 [
155 'rc_type != ' . $dbr->addQuotes( RC_EXTERNAL ), // Exclude external (Wikidata)
156 'rc_user != 0',
157 'rc_bot' => 0,
158 'rc_log_type != ' . $dbr->addQuotes( 'newusers' ) . ' OR rc_log_type IS NULL',
159 'rc_timestamp >= ' . $dbr->addQuotes(
160 $dbr->timestamp( time() - $config->get( 'ActiveUserDays' ) * 24 * 3600 ) ),
161 ],
162 __METHOD__
163 );
164 $dbw->update(
165 'site_stats',
166 [ 'ss_active_users' => intval( $activeUsers ) ],
167 [ 'ss_row_id' => 1 ],
168 __METHOD__
169 );
170
171 // Invalid cache used by parser functions
172 SiteStats::unload();
173
174 return $activeUsers;
175 }
176
177 protected function doUpdateContextStats() {
178 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
179 foreach ( [ 'edits', 'articles', 'pages', 'users', 'images' ] as $type ) {
180 $delta = $this->$type;
181 if ( $delta !== 0 ) {
182 $stats->updateCount( "site.$type", $delta );
183 }
184 }
185 }
186
187 protected function doUpdatePendingDeltas() {
188 $this->adjustPending( 'ss_total_edits', $this->edits );
189 $this->adjustPending( 'ss_good_articles', $this->articles );
190 $this->adjustPending( 'ss_total_pages', $this->pages );
191 $this->adjustPending( 'ss_users', $this->users );
192 $this->adjustPending( 'ss_images', $this->images );
193 }
194
195 /**
196 * @param string &$sql
197 * @param string $field
198 * @param int $delta
199 */
200 protected function appendUpdate( &$sql, $field, $delta ) {
201 if ( $delta ) {
202 if ( $sql ) {
203 $sql .= ',';
204 }
205 if ( $delta < 0 ) {
206 $sql .= "$field=$field-" . abs( $delta );
207 } else {
208 $sql .= "$field=$field+" . abs( $delta );
209 }
210 }
211 }
212
213 /**
214 * @param BagOStuff $stash
215 * @param string $type
216 * @param string $sign ('+' or '-')
217 * @return string
218 */
219 private function getTypeCacheKey( BagOStuff $stash, $type, $sign ) {
220 return $stash->makeKey( 'sitestatsupdate', 'pendingdelta', $type, $sign );
221 }
222
223 /**
224 * Adjust the pending deltas for a stat type.
225 * Each stat type has two pending counters, one for increments and decrements
226 * @param string $type
227 * @param int $delta Delta (positive or negative)
228 */
229 protected function adjustPending( $type, $delta ) {
230 if ( $delta < 0 ) { // decrement
231 $key = $this->getTypeCacheKey( $this->stash, $type, '-' );
232 } else { // increment
233 $key = $this->getTypeCacheKey( $this->stash, $type, '+' );
234 }
235
236 $magnitude = abs( $delta );
237 $this->stash->incrWithInit( $key, 0, $magnitude, $magnitude );
238 }
239
240 /**
241 * Get pending delta counters for each stat type
242 * @return array Positive and negative deltas for each type
243 */
244 protected function getPendingDeltas() {
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)$this->stash->get(
252 $this->getTypeCacheKey( $this->stash, $type, '+' ),
253 $flg
254 );
255 $pending[$type]['-'] = (int)$this->stash->get(
256 $this->getTypeCacheKey( $this->stash, $type, '-' ),
257 $flg
258 );
259 }
260
261 return $pending;
262 }
263
264 /**
265 * Reduce pending delta counters after updates have been applied
266 * @param array $pd Result of getPendingDeltas(), used for DB update
267 */
268 protected function removePendingDeltas( array $pd ) {
269 foreach ( $pd as $type => $deltas ) {
270 foreach ( $deltas as $sign => $magnitude ) {
271 // Lower the pending counter now that we applied these changes
272 $key = $this->getTypeCacheKey( $this->stash, $type, $sign );
273 $this->stash->decr( $key, $magnitude );
274 }
275 }
276 }
277 }