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