MediaWiki  master
RecentChangesUpdateJob.php
Go to the documentation of this file.
1 <?php
29 class RecentChangesUpdateJob extends Job {
31  parent::__construct( 'recentChangesUpdate', $title, $params );
32 
33  if ( !isset( $params['type'] ) ) {
34  throw new Exception( "Missing 'type' parameter." );
35  }
36 
37  $this->removeDuplicates = true;
38  }
39 
43  final public static function newPurgeJob() {
44  return new self(
45  SpecialPage::getTitleFor( 'Recentchanges' ), [ 'type' => 'purge' ]
46  );
47  }
48 
53  final public static function newCacheUpdateJob() {
54  return new self(
55  SpecialPage::getTitleFor( 'Recentchanges' ), [ 'type' => 'cacheUpdate' ]
56  );
57  }
58 
59  public function run() {
60  if ( $this->params['type'] === 'purge' ) {
61  $this->purgeExpiredRows();
62  } elseif ( $this->params['type'] === 'cacheUpdate' ) {
63  $this->updateActiveUsers();
64  } else {
65  throw new InvalidArgumentException(
66  "Invalid 'type' parameter '{$this->params['type']}'." );
67  }
68 
69  return true;
70  }
71 
72  protected function purgeExpiredRows() {
74 
75  $lockKey = wfWikiID() . ':recentchanges-prune';
76 
77  $dbw = wfGetDB( DB_MASTER );
78  if ( !$dbw->lockIsFree( $lockKey, __METHOD__ )
79  || !$dbw->lock( $lockKey, __METHOD__, 1 )
80  ) {
81  return; // already in progress
82  }
83 
84  $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
85  do {
86  $rcIds = $dbw->selectFieldValues( 'recentchanges',
87  'rc_id',
88  [ 'rc_timestamp < ' . $dbw->addQuotes( $cutoff ) ],
89  __METHOD__,
90  [ 'LIMIT' => $wgUpdateRowsPerQuery ]
91  );
92  if ( $rcIds ) {
93  $dbw->delete( 'recentchanges', [ 'rc_id' => $rcIds ], __METHOD__ );
94  }
95  // Commit in chunks to avoid slave lag
96  $dbw->commit( __METHOD__, 'flush' );
97 
98  if ( count( $rcIds ) === $wgUpdateRowsPerQuery ) {
99  // There might be more, so try waiting for slaves
100  try {
101  wfGetLBFactory()->waitForReplication( [ 'timeout' => 3 ] );
102  } catch ( DBReplicationWaitError $e ) {
103  // Another job will continue anyway
104  break;
105  }
106  }
107  } while ( $rcIds );
108 
109  $dbw->unlock( $lockKey, __METHOD__ );
110  }
111 
112  protected function updateActiveUsers() {
114 
115  // Users that made edits at least this many days ago are "active"
116  $days = $wgActiveUserDays;
117  // Pull in the full window of active users in this update
118  $window = $wgActiveUserDays * 86400;
119 
120  $dbw = wfGetDB( DB_MASTER );
121  // JobRunner uses DBO_TRX, but doesn't call begin/commit itself;
122  // onTransactionIdle() will run immediately since there is no trx.
123  $dbw->onTransactionIdle( function() use ( $dbw, $days, $window ) {
124  // Avoid disconnect/ping() cycle that makes locks fall off
125  $dbw->setSessionOptions( [ 'connTimeout' => 900 ] );
126 
127  $lockKey = wfWikiID() . '-activeusers';
128  if ( !$dbw->lock( $lockKey, __METHOD__, 1 ) ) {
129  return; // exclusive update (avoids duplicate entries)
130  }
131 
132  $nowUnix = time();
133  // Get the last-updated timestamp for the cache
134  $cTime = $dbw->selectField( 'querycache_info',
135  'qci_timestamp',
136  [ 'qci_type' => 'activeusers' ]
137  );
138  $cTimeUnix = $cTime ? wfTimestamp( TS_UNIX, $cTime ) : 1;
139 
140  // Pick the date range to fetch from. This is normally from the last
141  // update to till the present time, but has a limited window for sanity.
142  // If the window is limited, multiple runs are need to fully populate it.
143  $sTimestamp = max( $cTimeUnix, $nowUnix - $days * 86400 );
144  $eTimestamp = min( $sTimestamp + $window, $nowUnix );
145 
146  // Get all the users active since the last update
147  $res = $dbw->select(
148  [ 'recentchanges' ],
149  [ 'rc_user_text', 'lastedittime' => 'MAX(rc_timestamp)' ],
150  [
151  'rc_user > 0', // actual accounts
152  'rc_type != ' . $dbw->addQuotes( RC_EXTERNAL ), // no wikidata
153  'rc_log_type IS NULL OR rc_log_type != ' . $dbw->addQuotes( 'newusers' ),
154  'rc_timestamp >= ' . $dbw->addQuotes( $dbw->timestamp( $sTimestamp ) ),
155  'rc_timestamp <= ' . $dbw->addQuotes( $dbw->timestamp( $eTimestamp ) )
156  ],
157  __METHOD__,
158  [
159  'GROUP BY' => [ 'rc_user_text' ],
160  'ORDER BY' => 'NULL' // avoid filesort
161  ]
162  );
163  $names = [];
164  foreach ( $res as $row ) {
165  $names[$row->rc_user_text] = $row->lastedittime;
166  }
167 
168  // Rotate out users that have not edited in too long (according to old data set)
169  $dbw->delete( 'querycachetwo',
170  [
171  'qcc_type' => 'activeusers',
172  'qcc_value < ' . $dbw->addQuotes( $nowUnix - $days * 86400 ) // TS_UNIX
173  ],
174  __METHOD__
175  );
176 
177  // Find which of the recently active users are already accounted for
178  if ( count( $names ) ) {
179  $res = $dbw->select( 'querycachetwo',
180  [ 'user_name' => 'qcc_title' ],
181  [
182  'qcc_type' => 'activeusers',
183  'qcc_namespace' => NS_USER,
184  'qcc_title' => array_keys( $names ) ],
185  __METHOD__
186  );
187  foreach ( $res as $row ) {
188  unset( $names[$row->user_name] );
189  }
190  }
191 
192  // Insert the users that need to be added to the list
193  if ( count( $names ) ) {
194  $newRows = [];
195  foreach ( $names as $name => $lastEditTime ) {
196  $newRows[] = [
197  'qcc_type' => 'activeusers',
198  'qcc_namespace' => NS_USER,
199  'qcc_title' => $name,
200  'qcc_value' => wfTimestamp( TS_UNIX, $lastEditTime ),
201  'qcc_namespacetwo' => 0, // unused
202  'qcc_titletwo' => '' // unused
203  ];
204  }
205  foreach ( array_chunk( $newRows, 500 ) as $rowBatch ) {
206  $dbw->insert( 'querycachetwo', $rowBatch, __METHOD__ );
207  wfGetLBFactory()->waitForReplication();
208  }
209  }
210 
211  // If a transaction was already started, it might have an old
212  // snapshot, so kludge the timestamp range back as needed.
213  $asOfTimestamp = min( $eTimestamp, (int)$dbw->trxTimestamp() );
214 
215  // Touch the data freshness timestamp
216  $dbw->replace( 'querycache_info',
217  [ 'qci_type' ],
218  [ 'qci_type' => 'activeusers',
219  'qci_timestamp' => $dbw->timestamp( $asOfTimestamp ) ], // not always $now
220  __METHOD__
221  );
222 
223  $dbw->unlock( $lockKey, __METHOD__ );
224  } );
225  }
226 }
wfGetDB($db, $groups=[], $wiki=false)
Get a Database object.
the array() calling protocol came about after MediaWiki 1.4rc1.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
static getTitleFor($name, $subpage=false, $fragment= '')
Get a localised Title object for a specified special page name.
Definition: SpecialPage.php:80
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
Definition: hooks.txt:1980
Class to both describe a background job and handle jobs.
Definition: Job.php:31
Represents a title within MediaWiki.
Definition: Title.php:36
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
$wgRCMaxAge
Recentchanges items are periodically purged; entries older than this many seconds will go...
wfTimestamp($outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Exception class for replica DB wait timeouts.
Definition: LBFactory.php:472
$res
Definition: database.txt:21
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
__construct(Title $title, array $params)
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
$wgActiveUserDays
How many days user must be idle before he is considered inactive.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
wfGetLBFactory()
Get the load balancer factory object.
$wgUpdateRowsPerQuery
Number of rows to update per query.
array $params
Array of job parameters.
Definition: Job.php:36
const RC_EXTERNAL
Definition: Defines.php:172
const DB_MASTER
Definition: Defines.php:47
const TS_UNIX
Unix time - the number of seconds since 1970-01-01 00:00:00 UTC.
Title $title
Definition: Job.php:42
Job for pruning recent changes.
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:310