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.
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.
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
20 use Wikimedia\Assert\Assert
;
23 * Class for handling updates to the site_stats table
25 class SiteStatsUpdate
implements DeferrableUpdate
, MergeableUpdate
{
31 protected $articles = 0;
35 protected $images = 0;
37 private static $counters = [ 'edits', 'pages', 'articles', 'users', 'images' ];
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;
47 public function merge( MergeableUpdate
$update ) {
48 /** @var SiteStatsUpdate $update */
49 Assert
::parameterType( __CLASS__
, $update, '$update' );
51 foreach ( self
::$counters as $field ) {
52 $this->$field +
= $update->$field;
57 * @param array $deltas
58 * @return SiteStatsUpdate
60 public static function factory( array $deltas ) {
61 $update = new self( 0, 0, 0 );
63 foreach ( self
::$counters as $field ) {
64 if ( isset( $deltas[$field] ) && $deltas[$field] ) {
65 $update->$field = $deltas[$field];
72 public function doUpdate() {
73 global $wgSiteStatsAsyncFactor;
75 $this->doUpdateContextStats();
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();
83 // Need a separate transaction because this a global lock
84 DeferredUpdates
::addCallableUpdate( [ $this, 'tryDBUpdateInternal' ] );
89 * Do not call this outside of SiteStatsUpdate
91 public function tryDBUpdateInternal() {
92 global $wgSiteStatsAsyncFactor;
94 $dbw = wfGetDB( DB_MASTER
);
95 $lockKey = wfMemcKey( 'site_stats' ); // prepend wiki ID
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
102 $this->doUpdatePendingDeltas();
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']['-'] );
115 // Build up an SQL query of deltas and apply them...
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__
);
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__
);
133 // Invalid cache used by parser functions
138 * @param IDatabase $dbw
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(
148 'COUNT( DISTINCT rc_user_text )',
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 ) ),
160 [ 'ss_active_users' => intval( $activeUsers ) ],
161 [ 'ss_row_id' => 1 ],
165 // Invalid cache used by parser functions
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 );
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
);
191 * @param string $field
194 protected function appendUpdate( &$sql, $field, $delta ) {
200 $sql .= "$field=$field-" . abs( $delta );
202 $sql .= "$field=$field+" . abs( $delta );
208 * @param string $type
209 * @param string $sign ('+' or '-')
212 private function getTypeCacheKey( $type, $sign ) {
213 return wfMemcKey( 'sitestatsupdate', 'pendingdelta', $type, $sign );
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)
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, '+' );
230 $magnitude = abs( $delta );
231 $cache->incrWithInit( $key, 0, $magnitude, $magnitude );
235 * Get pending delta counters for each stat type
236 * @return array Positive and negative deltas for each type
238 protected function getPendingDeltas() {
239 $cache = ObjectCache
::getMainStashInstance();
242 foreach ( [ 'ss_total_edits',
243 'ss_good_articles', 'ss_total_pages', 'ss_users', 'ss_images' ] as $type
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 );
255 * Reduce pending delta counters after updates have been applied
256 * @param array $pd Result of getPendingDeltas(), used for DB update
258 protected function removePendingDeltas( array $pd ) {
259 $cache = ObjectCache
::getMainStashInstance();
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 );