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