MediaWiki  1.34.0
RecentChangesUpdateJob.php
Go to the documentation of this file.
1 <?php
22 
29 class RecentChangesUpdateJob extends Job {
30  function __construct( Title $title, array $params ) {
31  parent::__construct( 'recentChangesUpdate', $title, $params );
32 
33  if ( !isset( $params['type'] ) ) {
34  throw new Exception( "Missing 'type' parameter." );
35  }
36 
37  $this->executionFlags |= self::JOB_NO_EXPLICIT_TRX_ROUND;
38  $this->removeDuplicates = true;
39  }
40 
44  final public static function newPurgeJob() {
45  return new self(
46  SpecialPage::getTitleFor( 'Recentchanges' ), [ 'type' => 'purge' ]
47  );
48  }
49 
54  final public static function newCacheUpdateJob() {
55  return new self(
56  SpecialPage::getTitleFor( 'Recentchanges' ), [ 'type' => 'cacheUpdate' ]
57  );
58  }
59 
60  public function run() {
61  if ( $this->params['type'] === 'purge' ) {
62  $this->purgeExpiredRows();
63  } elseif ( $this->params['type'] === 'cacheUpdate' ) {
64  $this->updateActiveUsers();
65  } else {
66  throw new InvalidArgumentException(
67  "Invalid 'type' parameter '{$this->params['type']}'." );
68  }
69 
70  return true;
71  }
72 
73  protected function purgeExpiredRows() {
75 
76  $dbw = wfGetDB( DB_MASTER );
77  $lockKey = $dbw->getDomainID() . ':recentchanges-prune';
78  if ( !$dbw->lock( $lockKey, __METHOD__, 0 ) ) {
79  // already in progress
80  return;
81  }
82 
83  $factory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
84  $ticket = $factory->getEmptyTransactionTicket( __METHOD__ );
85  $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
86  $rcQuery = RecentChange::getQueryInfo();
87  do {
88  $rcIds = [];
89  $rows = [];
90  $res = $dbw->select(
91  $rcQuery['tables'],
92  $rcQuery['fields'],
93  [ 'rc_timestamp < ' . $dbw->addQuotes( $cutoff ) ],
94  __METHOD__,
95  [ 'LIMIT' => $wgUpdateRowsPerQuery ],
96  $rcQuery['joins']
97  );
98  foreach ( $res as $row ) {
99  $rcIds[] = $row->rc_id;
100  $rows[] = $row;
101  }
102  if ( $rcIds ) {
103  $dbw->delete( 'recentchanges', [ 'rc_id' => $rcIds ], __METHOD__ );
104  Hooks::run( 'RecentChangesPurgeRows', [ $rows ] );
105  // There might be more, so try waiting for replica DBs
106  if ( !$factory->commitAndWaitForReplication(
107  __METHOD__, $ticket, [ 'timeout' => 3 ]
108  ) ) {
109  // Another job will continue anyway
110  break;
111  }
112  }
113  } while ( $rcIds );
114 
115  $dbw->unlock( $lockKey, __METHOD__ );
116  }
117 
118  protected function updateActiveUsers() {
119  global $wgActiveUserDays;
120 
121  // Users that made edits at least this many days ago are "active"
122  $days = $wgActiveUserDays;
123  // Pull in the full window of active users in this update
124  $window = $wgActiveUserDays * 86400;
125 
126  $dbw = wfGetDB( DB_MASTER );
127  $factory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
128  $ticket = $factory->getEmptyTransactionTicket( __METHOD__ );
129 
130  $lockKey = $dbw->getDomainID() . '-activeusers';
131  if ( !$dbw->lock( $lockKey, __METHOD__, 0 ) ) {
132  // Exclusive update (avoids duplicate entries)… it's usually fine to just
133  // drop out here, if the Job is already running.
134  return;
135  }
136 
137  // Long-running queries expected
138  $dbw->setSessionOptions( [ 'connTimeout' => 900 ] );
139 
140  $nowUnix = time();
141  // Get the last-updated timestamp for the cache
142  $cTime = $dbw->selectField( 'querycache_info',
143  'qci_timestamp',
144  [ 'qci_type' => 'activeusers' ]
145  );
146  $cTimeUnix = $cTime ? wfTimestamp( TS_UNIX, $cTime ) : 1;
147 
148  // Pick the date range to fetch from. This is normally from the last
149  // update to till the present time, but has a limited window for sanity.
150  // If the window is limited, multiple runs are need to fully populate it.
151  $sTimestamp = max( $cTimeUnix, $nowUnix - $days * 86400 );
152  $eTimestamp = min( $sTimestamp + $window, $nowUnix );
153 
154  // Get all the users active since the last update
155  $actorQuery = ActorMigration::newMigration()->getJoin( 'rc_user' );
156  $res = $dbw->select(
157  [ 'recentchanges' ] + $actorQuery['tables'],
158  [
159  'rc_user_text' => $actorQuery['fields']['rc_user_text'],
160  'lastedittime' => 'MAX(rc_timestamp)'
161  ],
162  [
163  $actorQuery['fields']['rc_user'] . ' > 0', // actual accounts
164  'rc_type != ' . $dbw->addQuotes( RC_EXTERNAL ), // no wikidata
165  'rc_log_type IS NULL OR rc_log_type != ' . $dbw->addQuotes( 'newusers' ),
166  'rc_timestamp >= ' . $dbw->addQuotes( $dbw->timestamp( $sTimestamp ) ),
167  'rc_timestamp <= ' . $dbw->addQuotes( $dbw->timestamp( $eTimestamp ) )
168  ],
169  __METHOD__,
170  [
171  'GROUP BY' => [ $actorQuery['fields']['rc_user_text'] ],
172  'ORDER BY' => 'NULL' // avoid filesort
173  ],
174  $actorQuery['joins']
175  );
176  $names = [];
177  foreach ( $res as $row ) {
178  $names[$row->rc_user_text] = $row->lastedittime;
179  }
180 
181  // Find which of the recently active users are already accounted for
182  if ( count( $names ) ) {
183  $res = $dbw->select( 'querycachetwo',
184  [ 'user_name' => 'qcc_title' ],
185  [
186  'qcc_type' => 'activeusers',
187  'qcc_namespace' => NS_USER,
188  'qcc_title' => array_keys( $names ),
189  'qcc_value >= ' . $dbw->addQuotes( $nowUnix - $days * 86400 ), // TS_UNIX
190  ],
191  __METHOD__
192  );
193  // Note: In order for this to be actually consistent, we would need
194  // to update these rows with the new lastedittime.
195  foreach ( $res as $row ) {
196  unset( $names[$row->user_name] );
197  }
198  }
199 
200  // Insert the users that need to be added to the list
201  if ( count( $names ) ) {
202  $newRows = [];
203  foreach ( $names as $name => $lastEditTime ) {
204  $newRows[] = [
205  'qcc_type' => 'activeusers',
206  'qcc_namespace' => NS_USER,
207  'qcc_title' => $name,
208  'qcc_value' => wfTimestamp( TS_UNIX, $lastEditTime ),
209  'qcc_namespacetwo' => 0, // unused
210  'qcc_titletwo' => '' // unused
211  ];
212  }
213  foreach ( array_chunk( $newRows, 500 ) as $rowBatch ) {
214  $dbw->insert( 'querycachetwo', $rowBatch, __METHOD__ );
215  $factory->commitAndWaitForReplication( __METHOD__, $ticket );
216  }
217  }
218 
219  // If a transaction was already started, it might have an old
220  // snapshot, so kludge the timestamp range back as needed.
221  $asOfTimestamp = min( $eTimestamp, (int)$dbw->trxTimestamp() );
222 
223  // Touch the data freshness timestamp
224  $dbw->replace( 'querycache_info',
225  [ 'qci_type' ],
226  [ 'qci_type' => 'activeusers',
227  'qci_timestamp' => $dbw->timestamp( $asOfTimestamp ) ], // not always $now
228  __METHOD__
229  );
230 
231  $dbw->unlock( $lockKey, __METHOD__ );
232 
233  // Rotate out users that have not edited in too long (according to old data set)
234  $dbw->delete( 'querycachetwo',
235  [
236  'qcc_type' => 'activeusers',
237  'qcc_value < ' . $dbw->addQuotes( $nowUnix - $days * 86400 ) // TS_UNIX
238  ],
239  __METHOD__
240  );
241  }
242 }
RecentChange\getQueryInfo
static getQueryInfo()
Return the tables, fields, and join conditions to be selected to create a new recentchanges object.
Definition: RecentChange.php:233
RC_EXTERNAL
const RC_EXTERNAL
Definition: Defines.php:125
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:117
RecentChangesUpdateJob
Job for pruning recent changes.
Definition: RecentChangesUpdateJob.php:29
RecentChangesUpdateJob\updateActiveUsers
updateActiveUsers()
Definition: RecentChangesUpdateJob.php:118
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1869
RecentChangesUpdateJob\run
run()
Run the job.
Definition: RecentChangesUpdateJob.php:60
Job\$title
Title $title
Definition: Job.php:41
RecentChangesUpdateJob\__construct
__construct(Title $title, array $params)
Definition: RecentChangesUpdateJob.php:30
SpecialPage\getTitleFor
static getTitleFor( $name, $subpage=false, $fragment='')
Get a localised Title object for a specified special page name If you don't need a full Title object,...
Definition: SpecialPage.php:83
RecentChangesUpdateJob\purgeExpiredRows
purgeExpiredRows()
Definition: RecentChangesUpdateJob.php:73
$res
$res
Definition: testCompression.php:52
Job\$params
array $params
Array of job parameters.
Definition: Job.php:35
RecentChangesUpdateJob\newCacheUpdateJob
static newCacheUpdateJob()
Definition: RecentChangesUpdateJob.php:54
ActorMigration\newMigration
static newMigration()
Static constructor.
Definition: ActorMigration.php:136
Job
Class to both describe a background job and handle jobs.
Definition: Job.php:30
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2575
$wgUpdateRowsPerQuery
$wgUpdateRowsPerQuery
Number of rows to update per query.
Definition: DefaultSettings.php:8480
DB_MASTER
const DB_MASTER
Definition: defines.php:26
$wgActiveUserDays
$wgActiveUserDays
How many days user must be idle before he is considered inactive.
Definition: DefaultSettings.php:4386
$wgRCMaxAge
$wgRCMaxAge
Recentchanges items are periodically purged; entries older than this many seconds will go.
Definition: DefaultSettings.php:6801
Title
Represents a title within MediaWiki.
Definition: Title.php:42
RecentChangesUpdateJob\newPurgeJob
static newPurgeJob()
Definition: RecentChangesUpdateJob.php:44
NS_USER
const NS_USER
Definition: Defines.php:62
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200