RecentChangesUpdateJob.php 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. <?php
  2. /**
  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.
  7. *
  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.
  12. *
  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
  17. *
  18. * @file
  19. * @ingroup JobQueue
  20. */
  21. use MediaWiki\MediaWikiServices;
  22. /**
  23. * Job for pruning recent changes
  24. *
  25. * @ingroup JobQueue
  26. * @since 1.25
  27. */
  28. class RecentChangesUpdateJob extends Job {
  29. function __construct( Title $title, array $params ) {
  30. parent::__construct( 'recentChangesUpdate', $title, $params );
  31. if ( !isset( $params['type'] ) ) {
  32. throw new Exception( "Missing 'type' parameter." );
  33. }
  34. $this->executionFlags |= self::JOB_NO_EXPLICIT_TRX_ROUND;
  35. $this->removeDuplicates = true;
  36. }
  37. /**
  38. * @return RecentChangesUpdateJob
  39. */
  40. final public static function newPurgeJob() {
  41. return new self(
  42. SpecialPage::getTitleFor( 'Recentchanges' ), [ 'type' => 'purge' ]
  43. );
  44. }
  45. /**
  46. * @return RecentChangesUpdateJob
  47. * @since 1.26
  48. */
  49. final public static function newCacheUpdateJob() {
  50. return new self(
  51. SpecialPage::getTitleFor( 'Recentchanges' ), [ 'type' => 'cacheUpdate' ]
  52. );
  53. }
  54. public function run() {
  55. if ( $this->params['type'] === 'purge' ) {
  56. $this->purgeExpiredRows();
  57. } elseif ( $this->params['type'] === 'cacheUpdate' ) {
  58. $this->updateActiveUsers();
  59. } else {
  60. throw new InvalidArgumentException(
  61. "Invalid 'type' parameter '{$this->params['type']}'." );
  62. }
  63. return true;
  64. }
  65. protected function purgeExpiredRows() {
  66. global $wgRCMaxAge, $wgUpdateRowsPerQuery;
  67. $dbw = wfGetDB( DB_MASTER );
  68. $lockKey = $dbw->getDomainID() . ':recentchanges-prune';
  69. if ( !$dbw->lock( $lockKey, __METHOD__, 0 ) ) {
  70. // already in progress
  71. return;
  72. }
  73. $factory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
  74. $ticket = $factory->getEmptyTransactionTicket( __METHOD__ );
  75. $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
  76. $rcQuery = RecentChange::getQueryInfo();
  77. do {
  78. $rcIds = [];
  79. $rows = [];
  80. $res = $dbw->select(
  81. $rcQuery['tables'],
  82. $rcQuery['fields'],
  83. [ 'rc_timestamp < ' . $dbw->addQuotes( $cutoff ) ],
  84. __METHOD__,
  85. [ 'LIMIT' => $wgUpdateRowsPerQuery ],
  86. $rcQuery['joins']
  87. );
  88. foreach ( $res as $row ) {
  89. $rcIds[] = $row->rc_id;
  90. $rows[] = $row;
  91. }
  92. if ( $rcIds ) {
  93. $dbw->delete( 'recentchanges', [ 'rc_id' => $rcIds ], __METHOD__ );
  94. Hooks::run( 'RecentChangesPurgeRows', [ $rows ] );
  95. // There might be more, so try waiting for replica DBs
  96. if ( !$factory->commitAndWaitForReplication(
  97. __METHOD__, $ticket, [ 'timeout' => 3 ]
  98. ) ) {
  99. // Another job will continue anyway
  100. break;
  101. }
  102. }
  103. } while ( $rcIds );
  104. $dbw->unlock( $lockKey, __METHOD__ );
  105. }
  106. protected function updateActiveUsers() {
  107. global $wgActiveUserDays;
  108. // Users that made edits at least this many days ago are "active"
  109. $days = $wgActiveUserDays;
  110. // Pull in the full window of active users in this update
  111. $window = $wgActiveUserDays * 86400;
  112. $dbw = wfGetDB( DB_MASTER );
  113. $factory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
  114. $ticket = $factory->getEmptyTransactionTicket( __METHOD__ );
  115. $lockKey = $dbw->getDomainID() . '-activeusers';
  116. if ( !$dbw->lock( $lockKey, __METHOD__, 0 ) ) {
  117. // Exclusive update (avoids duplicate entries)… it's usually fine to just
  118. // drop out here, if the Job is already running.
  119. return;
  120. }
  121. // Long-running queries expected
  122. $dbw->setSessionOptions( [ 'connTimeout' => 900 ] );
  123. $nowUnix = time();
  124. // Get the last-updated timestamp for the cache
  125. $cTime = $dbw->selectField( 'querycache_info',
  126. 'qci_timestamp',
  127. [ 'qci_type' => 'activeusers' ]
  128. );
  129. $cTimeUnix = $cTime ? wfTimestamp( TS_UNIX, $cTime ) : 1;
  130. // Pick the date range to fetch from. This is normally from the last
  131. // update to till the present time, but has a limited window for sanity.
  132. // If the window is limited, multiple runs are need to fully populate it.
  133. $sTimestamp = max( $cTimeUnix, $nowUnix - $days * 86400 );
  134. $eTimestamp = min( $sTimestamp + $window, $nowUnix );
  135. // Get all the users active since the last update
  136. $actorQuery = ActorMigration::newMigration()->getJoin( 'rc_user' );
  137. $res = $dbw->select(
  138. [ 'recentchanges' ] + $actorQuery['tables'],
  139. [
  140. 'rc_user_text' => $actorQuery['fields']['rc_user_text'],
  141. 'lastedittime' => 'MAX(rc_timestamp)'
  142. ],
  143. [
  144. $actorQuery['fields']['rc_user'] . ' > 0', // actual accounts
  145. 'rc_type != ' . $dbw->addQuotes( RC_EXTERNAL ), // no wikidata
  146. 'rc_log_type IS NULL OR rc_log_type != ' . $dbw->addQuotes( 'newusers' ),
  147. 'rc_timestamp >= ' . $dbw->addQuotes( $dbw->timestamp( $sTimestamp ) ),
  148. 'rc_timestamp <= ' . $dbw->addQuotes( $dbw->timestamp( $eTimestamp ) )
  149. ],
  150. __METHOD__,
  151. [
  152. 'GROUP BY' => [ $actorQuery['fields']['rc_user_text'] ],
  153. 'ORDER BY' => 'NULL' // avoid filesort
  154. ],
  155. $actorQuery['joins']
  156. );
  157. $names = [];
  158. foreach ( $res as $row ) {
  159. $names[$row->rc_user_text] = $row->lastedittime;
  160. }
  161. // Find which of the recently active users are already accounted for
  162. if ( count( $names ) ) {
  163. $res = $dbw->select( 'querycachetwo',
  164. [ 'user_name' => 'qcc_title' ],
  165. [
  166. 'qcc_type' => 'activeusers',
  167. 'qcc_namespace' => NS_USER,
  168. 'qcc_title' => array_keys( $names ),
  169. 'qcc_value >= ' . $dbw->addQuotes( $nowUnix - $days * 86400 ), // TS_UNIX
  170. ],
  171. __METHOD__
  172. );
  173. // Note: In order for this to be actually consistent, we would need
  174. // to update these rows with the new lastedittime.
  175. foreach ( $res as $row ) {
  176. unset( $names[$row->user_name] );
  177. }
  178. }
  179. // Insert the users that need to be added to the list
  180. if ( count( $names ) ) {
  181. $newRows = [];
  182. foreach ( $names as $name => $lastEditTime ) {
  183. $newRows[] = [
  184. 'qcc_type' => 'activeusers',
  185. 'qcc_namespace' => NS_USER,
  186. 'qcc_title' => $name,
  187. 'qcc_value' => wfTimestamp( TS_UNIX, $lastEditTime ),
  188. 'qcc_namespacetwo' => 0, // unused
  189. 'qcc_titletwo' => '' // unused
  190. ];
  191. }
  192. foreach ( array_chunk( $newRows, 500 ) as $rowBatch ) {
  193. $dbw->insert( 'querycachetwo', $rowBatch, __METHOD__ );
  194. $factory->commitAndWaitForReplication( __METHOD__, $ticket );
  195. }
  196. }
  197. // If a transaction was already started, it might have an old
  198. // snapshot, so kludge the timestamp range back as needed.
  199. $asOfTimestamp = min( $eTimestamp, (int)$dbw->trxTimestamp() );
  200. // Touch the data freshness timestamp
  201. $dbw->replace( 'querycache_info',
  202. [ 'qci_type' ],
  203. [ 'qci_type' => 'activeusers',
  204. 'qci_timestamp' => $dbw->timestamp( $asOfTimestamp ) ], // not always $now
  205. __METHOD__
  206. );
  207. $dbw->unlock( $lockKey, __METHOD__ );
  208. // Rotate out users that have not edited in too long (according to old data set)
  209. $dbw->delete( 'querycachetwo',
  210. [
  211. 'qcc_type' => 'activeusers',
  212. 'qcc_value < ' . $dbw->addQuotes( $nowUnix - $days * 86400 ) // TS_UNIX
  213. ],
  214. __METHOD__
  215. );
  216. }
  217. }