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 MediaWiki\MediaWikiServices
;
21 use Wikimedia\Assert\Assert
;
22 use Wikimedia\Rdbms\IDatabase
;
25 * Class for handling updates to the site_stats table
27 class SiteStatsUpdate
implements DeferrableUpdate
, MergeableUpdate
{
33 protected $articles = 0;
37 protected $images = 0;
39 private static $counters = [ 'edits', 'pages', 'articles', 'users', 'images' ];
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;
49 public function merge( MergeableUpdate
$update ) {
50 /** @var SiteStatsUpdate $update */
51 Assert
::parameterType( __CLASS__
, $update, '$update' );
53 foreach ( self
::$counters as $field ) {
54 $this->$field +
= $update->$field;
59 * @param array $deltas
60 * @return SiteStatsUpdate
62 public static function factory( array $deltas ) {
63 $update = new self( 0, 0, 0 );
65 foreach ( self
::$counters as $field ) {
66 if ( isset( $deltas[$field] ) && $deltas[$field] ) {
67 $update->$field = $deltas[$field];
74 public function doUpdate() {
75 global $wgSiteStatsAsyncFactor;
77 $this->doUpdateContextStats();
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();
85 // Need a separate transaction because this a global lock
86 DeferredUpdates
::addCallableUpdate( [ $this, 'tryDBUpdateInternal' ] );
91 * Do not call this outside of SiteStatsUpdate
93 public function tryDBUpdateInternal() {
94 global $wgSiteStatsAsyncFactor;
96 $dbw = wfGetDB( DB_MASTER
);
97 $lockKey = wfWikiID() . ':site_stats'; // prepend wiki ID
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
104 $this->doUpdatePendingDeltas();
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']['-'] );
117 // Build up an SQL query of deltas and apply them...
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__
);
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__
);
135 // Invalid cache used by parser functions
140 * @param IDatabase $dbw
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(
150 'COUNT( DISTINCT rc_user_text )',
152 'rc_type != ' . $dbr->addQuotes( RC_EXTERNAL
), // Exclude external (Wikidata)
155 'rc_log_type != ' . $dbr->addQuotes( 'newusers' ) . ' OR rc_log_type IS NULL',
156 'rc_timestamp >= ' . $dbr->addQuotes( $dbr->timestamp( wfTimestamp( TS_UNIX
)
157 - $wgActiveUserDays * 24 * 3600 ) ),
163 [ 'ss_active_users' => intval( $activeUsers ) ],
164 [ 'ss_row_id' => 1 ],
168 // Invalid cache used by parser functions
174 protected function doUpdateContextStats() {
175 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
176 foreach ( [ 'edits', 'articles', 'pages', 'users', 'images' ] as $type ) {
177 $delta = $this->$type;
178 if ( $delta !== 0 ) {
179 $stats->updateCount( "site.$type", $delta );
184 protected function doUpdatePendingDeltas() {
185 $this->adjustPending( 'ss_total_edits', $this->edits
);
186 $this->adjustPending( 'ss_good_articles', $this->articles
);
187 $this->adjustPending( 'ss_total_pages', $this->pages
);
188 $this->adjustPending( 'ss_users', $this->users
);
189 $this->adjustPending( 'ss_images', $this->images
);
193 * @param string &$sql
194 * @param string $field
197 protected function appendUpdate( &$sql, $field, $delta ) {
203 $sql .= "$field=$field-" . abs( $delta );
205 $sql .= "$field=$field+" . abs( $delta );
211 * @param BagOStuff $cache
212 * @param string $type
213 * @param string $sign ('+' or '-')
216 private function getTypeCacheKey( BagOStuff
$cache, $type, $sign ) {
217 return $cache->makeKey( 'sitestatsupdate', 'pendingdelta', $type, $sign );
221 * Adjust the pending deltas for a stat type.
222 * Each stat type has two pending counters, one for increments and decrements
223 * @param string $type
224 * @param int $delta Delta (positive or negative)
226 protected function adjustPending( $type, $delta ) {
227 $cache = MediaWikiServices
::getInstance()->getMainObjectStash();
228 if ( $delta < 0 ) { // decrement
229 $key = $this->getTypeCacheKey( $cache, $type, '-' );
230 } else { // increment
231 $key = $this->getTypeCacheKey( $cache, $type, '+' );
234 $magnitude = abs( $delta );
235 $cache->incrWithInit( $key, 0, $magnitude, $magnitude );
239 * Get pending delta counters for each stat type
240 * @return array Positive and negative deltas for each type
242 protected function getPendingDeltas() {
243 $cache = MediaWikiServices
::getInstance()->getMainObjectStash();
246 foreach ( [ 'ss_total_edits',
247 'ss_good_articles', 'ss_total_pages', 'ss_users', 'ss_images' ] as $type
249 // Get pending increments and pending decrements
250 $flg = BagOStuff
::READ_LATEST
;
251 $pending[$type]['+'] = (int)$cache->get( $this->getTypeCacheKey( $cache, $type, '+' ), $flg );
252 $pending[$type]['-'] = (int)$cache->get( $this->getTypeCacheKey( $cache, $type, '-' ), $flg );
259 * Reduce pending delta counters after updates have been applied
260 * @param array $pd Result of getPendingDeltas(), used for DB update
262 protected function removePendingDeltas( array $pd ) {
263 $cache = MediaWikiServices
::getInstance()->getMainObjectStash();
265 foreach ( $pd as $type => $deltas ) {
266 foreach ( $deltas as $sign => $magnitude ) {
267 // Lower the pending counter now that we applied these changes
268 $cache->decr( $this->getTypeCacheKey( $cache, $type, $sign ), $magnitude );