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 )',
154 'rc_log_type != ' . $dbr->addQuotes( 'newusers' ) . ' OR rc_log_type IS NULL',
155 'rc_timestamp >= ' . $dbr->addQuotes( $dbr->timestamp( wfTimestamp( TS_UNIX
)
156 - $wgActiveUserDays * 24 * 3600 ) ),
162 [ 'ss_active_users' => intval( $activeUsers ) ],
163 [ 'ss_row_id' => 1 ],
167 // Invalid cache used by parser functions
173 protected function doUpdateContextStats() {
174 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
175 foreach ( [ 'edits', 'articles', 'pages', 'users', 'images' ] as $type ) {
176 $delta = $this->$type;
177 if ( $delta !== 0 ) {
178 $stats->updateCount( "site.$type", $delta );
183 protected function doUpdatePendingDeltas() {
184 $this->adjustPending( 'ss_total_edits', $this->edits
);
185 $this->adjustPending( 'ss_good_articles', $this->articles
);
186 $this->adjustPending( 'ss_total_pages', $this->pages
);
187 $this->adjustPending( 'ss_users', $this->users
);
188 $this->adjustPending( 'ss_images', $this->images
);
192 * @param string &$sql
193 * @param string $field
196 protected function appendUpdate( &$sql, $field, $delta ) {
202 $sql .= "$field=$field-" . abs( $delta );
204 $sql .= "$field=$field+" . abs( $delta );
210 * @param BagOStuff $cache
211 * @param string $type
212 * @param string $sign ('+' or '-')
215 private function getTypeCacheKey( BagOStuff
$cache, $type, $sign ) {
216 return $cache->makeKey( 'sitestatsupdate', 'pendingdelta', $type, $sign );
220 * Adjust the pending deltas for a stat type.
221 * Each stat type has two pending counters, one for increments and decrements
222 * @param string $type
223 * @param int $delta Delta (positive or negative)
225 protected function adjustPending( $type, $delta ) {
226 $cache = MediaWikiServices
::getInstance()->getMainObjectStash();
227 if ( $delta < 0 ) { // decrement
228 $key = $this->getTypeCacheKey( $cache, $type, '-' );
229 } else { // increment
230 $key = $this->getTypeCacheKey( $cache, $type, '+' );
233 $magnitude = abs( $delta );
234 $cache->incrWithInit( $key, 0, $magnitude, $magnitude );
238 * Get pending delta counters for each stat type
239 * @return array Positive and negative deltas for each type
241 protected function getPendingDeltas() {
242 $cache = MediaWikiServices
::getInstance()->getMainObjectStash();
245 foreach ( [ 'ss_total_edits',
246 'ss_good_articles', 'ss_total_pages', 'ss_users', 'ss_images' ] as $type
248 // Get pending increments and pending decrements
249 $flg = BagOStuff
::READ_LATEST
;
250 $pending[$type]['+'] = (int)$cache->get( $this->getTypeCacheKey( $cache, $type, '+' ), $flg );
251 $pending[$type]['-'] = (int)$cache->get( $this->getTypeCacheKey( $cache, $type, '-' ), $flg );
258 * Reduce pending delta counters after updates have been applied
259 * @param array $pd Result of getPendingDeltas(), used for DB update
261 protected function removePendingDeltas( array $pd ) {
262 $cache = MediaWikiServices
::getInstance()->getMainObjectStash();
264 foreach ( $pd as $type => $deltas ) {
265 foreach ( $deltas as $sign => $magnitude ) {
266 // Lower the pending counter now that we applied these changes
267 $cache->decr( $this->getTypeCacheKey( $cache, $type, $sign ), $magnitude );