CategoryMembershipChangeJob.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. <?php
  2. /**
  3. * Updater for link tracking tables after a page edit.
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License along
  16. * with this program; if not, write to the Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. * http://www.gnu.org/copyleft/gpl.html
  19. *
  20. * @file
  21. */
  22. use MediaWiki\MediaWikiServices;
  23. use Wikimedia\Rdbms\LBFactory;
  24. /**
  25. * Job to add recent change entries mentioning category membership changes
  26. *
  27. * This allows users to easily scan categories for recent page membership changes
  28. *
  29. * Parameters include:
  30. * - pageId : page ID
  31. * - revTimestamp : timestamp of the triggering revision
  32. *
  33. * Category changes will be mentioned for revisions at/after the timestamp for this page
  34. *
  35. * @since 1.27
  36. */
  37. class CategoryMembershipChangeJob extends Job {
  38. /** @var int|null */
  39. private $ticket;
  40. const ENQUEUE_FUDGE_SEC = 60;
  41. /**
  42. * @var ParserCache
  43. */
  44. private $parserCache;
  45. /**
  46. * @param Title $title The title of the page for which to update category membership.
  47. * @param string $revisionTimestamp The timestamp of the new revision that triggered the job.
  48. * @return JobSpecification
  49. */
  50. public static function newSpec( Title $title, $revisionTimestamp ) {
  51. return new JobSpecification(
  52. 'categoryMembershipChange',
  53. [
  54. 'pageId' => $title->getArticleID(),
  55. 'revTimestamp' => $revisionTimestamp,
  56. ],
  57. [],
  58. $title
  59. );
  60. }
  61. /**
  62. * Constructor for use by the Job Queue infrastructure.
  63. * @note Don't call this when queueing a new instance, use newSpec() instead.
  64. * @param ParserCache $parserCache Cache outputs of PHP parser.
  65. * @param Title $title Title of the categorized page.
  66. * @param array $params Such latest revision instance of the categorized page.
  67. */
  68. public function __construct( ParserCache $parserCache, Title $title, array $params ) {
  69. parent::__construct( 'categoryMembershipChange', $title, $params );
  70. // Only need one job per page. Note that ENQUEUE_FUDGE_SEC handles races where an
  71. // older revision job gets inserted while the newer revision job is de-duplicated.
  72. $this->removeDuplicates = true;
  73. $this->parserCache = $parserCache;
  74. }
  75. public function run() {
  76. $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
  77. $lb = $lbFactory->getMainLB();
  78. $dbw = $lb->getConnectionRef( DB_MASTER );
  79. $this->ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__ );
  80. $page = WikiPage::newFromID( $this->params['pageId'], WikiPage::READ_LATEST );
  81. if ( !$page ) {
  82. $this->setLastError( "Could not find page #{$this->params['pageId']}" );
  83. return false; // deleted?
  84. }
  85. // Cut down on the time spent in waitForMasterPos() in the critical section
  86. $dbr = $lb->getConnectionRef( DB_REPLICA, [ 'recentchanges' ] );
  87. if ( !$lb->waitForMasterPos( $dbr ) ) {
  88. $this->setLastError( "Timed out while pre-waiting for replica DB to catch up" );
  89. return false;
  90. }
  91. // Use a named lock so that jobs for this page see each others' changes
  92. $lockKey = "{$dbw->getDomainID()}:CategoryMembershipChange:{$page->getId()}"; // per-wiki
  93. $scopedLock = $dbw->getScopedLockAndFlush( $lockKey, __METHOD__, 3 );
  94. if ( !$scopedLock ) {
  95. $this->setLastError( "Could not acquire lock '$lockKey'" );
  96. return false;
  97. }
  98. // Wait till replica DB is caught up so that jobs for this page see each others' changes
  99. if ( !$lb->waitForMasterPos( $dbr ) ) {
  100. $this->setLastError( "Timed out while waiting for replica DB to catch up" );
  101. return false;
  102. }
  103. // Clear any stale REPEATABLE-READ snapshot
  104. $dbr->flushSnapshot( __METHOD__ );
  105. $cutoffUnix = wfTimestamp( TS_UNIX, $this->params['revTimestamp'] );
  106. // Using ENQUEUE_FUDGE_SEC handles jobs inserted out of revision order due to the delay
  107. // between COMMIT and actual enqueueing of the CategoryMembershipChangeJob job.
  108. $cutoffUnix -= self::ENQUEUE_FUDGE_SEC;
  109. // Get the newest page revision that has a SRC_CATEGORIZE row.
  110. // Assume that category changes before it were already handled.
  111. $row = $dbr->selectRow(
  112. 'revision',
  113. [ 'rev_timestamp', 'rev_id' ],
  114. [
  115. 'rev_page' => $page->getId(),
  116. 'rev_timestamp >= ' . $dbr->addQuotes( $dbr->timestamp( $cutoffUnix ) ),
  117. 'EXISTS (' . $dbr->selectSQLText(
  118. 'recentchanges',
  119. '1',
  120. [
  121. 'rc_this_oldid = rev_id',
  122. 'rc_source' => RecentChange::SRC_CATEGORIZE,
  123. // Allow rc_cur_id or rc_timestamp index usage
  124. 'rc_cur_id = rev_page',
  125. 'rc_timestamp = rev_timestamp'
  126. ]
  127. ) . ')'
  128. ],
  129. __METHOD__,
  130. [ 'ORDER BY' => 'rev_timestamp DESC, rev_id DESC' ]
  131. );
  132. // Only consider revisions newer than any such revision
  133. if ( $row ) {
  134. $cutoffUnix = wfTimestamp( TS_UNIX, $row->rev_timestamp );
  135. $lastRevId = (int)$row->rev_id;
  136. } else {
  137. $lastRevId = 0;
  138. }
  139. // Find revisions to this page made around and after this revision which lack category
  140. // notifications in recent changes. This lets jobs pick up were the last one left off.
  141. $encCutoff = $dbr->addQuotes( $dbr->timestamp( $cutoffUnix ) );
  142. $revQuery = Revision::getQueryInfo();
  143. $res = $dbr->select(
  144. $revQuery['tables'],
  145. $revQuery['fields'],
  146. [
  147. 'rev_page' => $page->getId(),
  148. "rev_timestamp > $encCutoff" .
  149. " OR (rev_timestamp = $encCutoff AND rev_id > $lastRevId)"
  150. ],
  151. __METHOD__,
  152. [ 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC' ],
  153. $revQuery['joins']
  154. );
  155. // Apply all category updates in revision timestamp order
  156. foreach ( $res as $row ) {
  157. $this->notifyUpdatesForRevision( $lbFactory, $page, Revision::newFromRow( $row ) );
  158. }
  159. return true;
  160. }
  161. /**
  162. * @param LBFactory $lbFactory
  163. * @param WikiPage $page
  164. * @param Revision $newRev
  165. * @throws MWException
  166. */
  167. protected function notifyUpdatesForRevision(
  168. LBFactory $lbFactory, WikiPage $page, Revision $newRev
  169. ) {
  170. $config = RequestContext::getMain()->getConfig();
  171. $title = $page->getTitle();
  172. // Get the new revision
  173. if ( !$newRev->getContent() ) {
  174. return; // deleted?
  175. }
  176. // Get the prior revision (the same for null edits)
  177. if ( $newRev->getParentId() ) {
  178. $oldRev = Revision::newFromId( $newRev->getParentId(), Revision::READ_LATEST );
  179. if ( !$oldRev || !$oldRev->getContent() ) {
  180. return; // deleted?
  181. }
  182. } else {
  183. $oldRev = null;
  184. }
  185. // Parse the new revision and get the categories
  186. $categoryChanges = $this->getExplicitCategoriesChanges( $page, $newRev, $oldRev );
  187. list( $categoryInserts, $categoryDeletes ) = $categoryChanges;
  188. if ( !$categoryInserts && !$categoryDeletes ) {
  189. return; // nothing to do
  190. }
  191. $catMembChange = new CategoryMembershipChange( $title, $newRev );
  192. $catMembChange->checkTemplateLinks();
  193. $batchSize = $config->get( 'UpdateRowsPerQuery' );
  194. $insertCount = 0;
  195. foreach ( $categoryInserts as $categoryName ) {
  196. $categoryTitle = Title::makeTitle( NS_CATEGORY, $categoryName );
  197. $catMembChange->triggerCategoryAddedNotification( $categoryTitle );
  198. if ( $insertCount++ && ( $insertCount % $batchSize ) == 0 ) {
  199. $lbFactory->commitAndWaitForReplication( __METHOD__, $this->ticket );
  200. }
  201. }
  202. foreach ( $categoryDeletes as $categoryName ) {
  203. $categoryTitle = Title::makeTitle( NS_CATEGORY, $categoryName );
  204. $catMembChange->triggerCategoryRemovedNotification( $categoryTitle );
  205. if ( $insertCount++ && ( $insertCount++ % $batchSize ) == 0 ) {
  206. $lbFactory->commitAndWaitForReplication( __METHOD__, $this->ticket );
  207. }
  208. }
  209. }
  210. private function getExplicitCategoriesChanges(
  211. WikiPage $page, Revision $newRev, Revision $oldRev = null
  212. ) {
  213. // Inject the same timestamp for both revision parses to avoid seeing category changes
  214. // due to time-based parser functions. Inject the same page title for the parses too.
  215. // Note that REPEATABLE-READ makes template/file pages appear unchanged between parses.
  216. $parseTimestamp = $newRev->getTimestamp();
  217. // Parse the old rev and get the categories. Do not use link tables as that
  218. // assumes these updates are perfectly FIFO and that link tables are always
  219. // up to date, neither of which are true.
  220. $oldCategories = $oldRev
  221. ? $this->getCategoriesAtRev( $page, $oldRev, $parseTimestamp )
  222. : [];
  223. // Parse the new revision and get the categories
  224. $newCategories = $this->getCategoriesAtRev( $page, $newRev, $parseTimestamp );
  225. $categoryInserts = array_values( array_diff( $newCategories, $oldCategories ) );
  226. $categoryDeletes = array_values( array_diff( $oldCategories, $newCategories ) );
  227. return [ $categoryInserts, $categoryDeletes ];
  228. }
  229. /**
  230. * @param WikiPage $page
  231. * @param Revision $rev
  232. * @param string $parseTimestamp TS_MW
  233. *
  234. * @return string[] category names
  235. */
  236. private function getCategoriesAtRev( WikiPage $page, Revision $rev, $parseTimestamp ) {
  237. $renderer = MediaWikiServices::getInstance()->getRevisionRenderer();
  238. $options = $page->makeParserOptions( 'canonical' );
  239. $options->setTimestamp( $parseTimestamp );
  240. $output = $rev->isCurrent() ? $this->parserCache->get( $page, $options ) : null;
  241. if ( !$output || $output->getCacheRevisionId() !== $rev->getId() ) {
  242. $output = $renderer->getRenderedRevision( $rev->getRevisionRecord(), $options )
  243. ->getRevisionParserOutput();
  244. }
  245. // array keys will cast numeric category names to ints
  246. // so we need to cast them back to strings to avoid breaking things!
  247. return array_map( 'strval', array_keys( $output->getCategories() ) );
  248. }
  249. public function getDeduplicationInfo() {
  250. $info = parent::getDeduplicationInfo();
  251. unset( $info['params']['revTimestamp'] ); // first job wins
  252. return $info;
  253. }
  254. }