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