Merge "Type hint against LinkTarget in WatchedItemStore"
[lhc/web/wiklou.git] / includes / libs / rdbms / lbfactory / ILBFactory.php
1 <?php
2 /**
3 * Generator and manager of database load balancing objects
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 * @ingroup Database
22 */
23
24 namespace Wikimedia\Rdbms;
25
26 use InvalidArgumentException;
27
28 /**
29 * An interface for generating database load balancers
30 * @ingroup Database
31 * @since 1.28
32 */
33 interface ILBFactory {
34 const SHUTDOWN_NO_CHRONPROT = 0; // don't save DB positions at all
35 const SHUTDOWN_CHRONPROT_ASYNC = 1; // save DB positions, but don't wait on remote DCs
36 const SHUTDOWN_CHRONPROT_SYNC = 2; // save DB positions, waiting on all DCs
37
38 /**
39 * Construct a manager of ILoadBalancer objects
40 *
41 * Sub-classes will extend the required keys in $conf with additional parameters
42 *
43 * @param array $conf Array with keys:
44 * - localDomain: A DatabaseDomain or domain ID string.
45 * - readOnlyReason: Reason the master DB is read-only if so [optional]
46 * - srvCache: BagOStuff object for server cache [optional]
47 * - memStash: BagOStuff object for cross-datacenter memory storage [optional]
48 * - wanCache: WANObjectCache object [optional]
49 * - hostname: The name of the current server [optional]
50 * - cliMode: Whether the execution context is a CLI script. [optional]
51 * - maxLag: Try to avoid DB replicas with lag above this many seconds [optional]
52 * - profiler: Class name or instance with profileIn()/profileOut() methods. [optional]
53 * - trxProfiler: TransactionProfiler instance. [optional]
54 * - replLogger: PSR-3 logger instance. [optional]
55 * - connLogger: PSR-3 logger instance. [optional]
56 * - queryLogger: PSR-3 logger instance. [optional]
57 * - perfLogger: PSR-3 logger instance. [optional]
58 * - errorLogger: Callback that takes an Exception and logs it. [optional]
59 * - deprecationLogger: Callback to log a deprecation warning. [optional]
60 * - secret: Secret string to use for HMAC hashing [optional]
61 * @throws InvalidArgumentException
62 */
63 public function __construct( array $conf );
64
65 /**
66 * Disables all load balancers. All connections are closed, and any attempt to
67 * open a new connection will result in a DBAccessError.
68 * @see ILoadBalancer::disable()
69 */
70 public function destroy();
71
72 /**
73 * Get the local (and default) database domain ID of connection handles
74 *
75 * @see DatabaseDomain
76 * @return string Database domain ID; this specifies DB name, schema, and table prefix
77 * @since 1.32
78 */
79 public function getLocalDomainID();
80
81 /**
82 * @param DatabaseDomain|string|bool $domain Database domain
83 * @return string Value of $domain if provided or the local domain otherwise
84 * @since 1.32
85 */
86 public function resolveDomainID( $domain );
87
88 /**
89 * Close all connection and redefine the local domain for testing or schema creation
90 *
91 * @param DatabaseDomain|string $domain
92 * @since 1.33
93 */
94 public function redefineLocalDomain( $domain );
95
96 /**
97 * Create a new load balancer object. The resulting object will be untracked,
98 * not chronology-protected, and the caller is responsible for cleaning it up.
99 *
100 * This method is for only advanced usage and callers should almost always use
101 * getMainLB() instead. This method can be useful when a table is used as a key/value
102 * store. In that cases, one might want to query it in autocommit mode (DBO_TRX off)
103 * but still use DBO_TRX transaction rounds on other tables.
104 *
105 * @param bool|string $domain Domain ID, or false for the current domain
106 * @return ILoadBalancer
107 */
108 public function newMainLB( $domain = false );
109
110 /**
111 * Get a cached (tracked) load balancer object.
112 *
113 * @param bool|string $domain Domain ID, or false for the current domain
114 * @return ILoadBalancer
115 */
116 public function getMainLB( $domain = false );
117
118 /**
119 * Create a new load balancer for external storage. The resulting object will be
120 * untracked, not chronology-protected, and the caller is responsible for cleaning it up.
121 *
122 * This method is for only advanced usage and callers should almost always use
123 * getExternalLB() instead. This method can be useful when a table is used as a
124 * key/value store. In that cases, one might want to query it in autocommit mode
125 * (DBO_TRX off) but still use DBO_TRX transaction rounds on other tables.
126 *
127 * @param string $cluster External storage cluster name
128 * @return ILoadBalancer
129 */
130 public function newExternalLB( $cluster );
131
132 /**
133 * Get a cached (tracked) load balancer for external storage
134 *
135 * @param string $cluster External storage cluster name
136 * @return ILoadBalancer
137 */
138 public function getExternalLB( $cluster );
139
140 /**
141 * Get cached (tracked) load balancers for all main database clusters
142 *
143 * @return ILoadBalancer[] Map of (cluster name => ILoadBalancer)
144 * @since 1.29
145 */
146 public function getAllMainLBs();
147
148 /**
149 * Get cached (tracked) load balancers for all external database clusters
150 *
151 * @return ILoadBalancer[] Map of (cluster name => ILoadBalancer)
152 * @since 1.29
153 */
154 public function getAllExternalLBs();
155
156 /**
157 * Execute a function for each tracked load balancer
158 * The callback is called with the load balancer as the first parameter,
159 * and $params passed as the subsequent parameters.
160 *
161 * @param callable $callback
162 * @param array $params
163 */
164 public function forEachLB( $callback, array $params = [] );
165
166 /**
167 * Prepare all tracked load balancers for shutdown
168 * @param int $mode One of the class SHUTDOWN_* constants
169 * @param callable|null $workCallback Work to mask ChronologyProtector writes
170 * @param int|null &$cpIndex Position key write counter for ChronologyProtector
171 * @param string|null &$cpClientId Client ID hash for ChronologyProtector
172 */
173 public function shutdown(
174 $mode = self::SHUTDOWN_CHRONPROT_SYNC,
175 callable $workCallback = null,
176 &$cpIndex = null,
177 &$cpClientId = null
178 );
179
180 /**
181 * Commit all replica DB transactions so as to flush any REPEATABLE-READ or SSI snapshot
182 *
183 * This is useful for getting rid of stale data from an implicit transaction round
184 *
185 * @param string $fname Caller name
186 */
187 public function flushReplicaSnapshots( $fname = __METHOD__ );
188
189 /**
190 * Commit open transactions on all connections. This is useful for two main cases:
191 * - a) To commit changes to the masters.
192 * - b) To release the snapshot on all connections, master and replica DBs.
193 * @param string $fname Caller name
194 * @param array $options Options map:
195 * - maxWriteDuration: abort if more than this much time was spent in write queries
196 */
197 public function commitAll( $fname = __METHOD__, array $options = [] );
198
199 /**
200 * Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
201 *
202 * The DBO_TRX setting will be reverted to the default in each of these methods:
203 * - commitMasterChanges()
204 * - rollbackMasterChanges()
205 * - commitAll()
206 *
207 * This allows for custom transaction rounds from any outer transaction scope.
208 *
209 * @param string $fname
210 * @throws DBTransactionError
211 */
212 public function beginMasterChanges( $fname = __METHOD__ );
213
214 /**
215 * Commit changes and clear view snapshots on all master connections
216 * @param string $fname Caller name
217 * @param array $options Options map:
218 * - maxWriteDuration: abort if more than this much time was spent in write queries
219 * @throws DBTransactionError
220 */
221 public function commitMasterChanges( $fname = __METHOD__, array $options = [] );
222
223 /**
224 * Rollback changes on all master connections
225 * @param string $fname Caller name
226 */
227 public function rollbackMasterChanges( $fname = __METHOD__ );
228
229 /**
230 * Check if an explicit transaction round is active
231 * @return bool
232 * @since 1.29
233 */
234 public function hasTransactionRound();
235
236 /**
237 * Check if transaction rounds can be started, committed, or rolled back right now
238 *
239 * This can be used as a recusion guard to avoid exceptions in transaction callbacks
240 *
241 * @return bool
242 * @since 1.32
243 */
244 public function isReadyForRoundOperations();
245
246 /**
247 * Determine if any master connection has pending changes
248 * @return bool
249 */
250 public function hasMasterChanges();
251
252 /**
253 * Detemine if any lagged replica DB connection was used
254 * @return bool
255 */
256 public function laggedReplicaUsed();
257
258 /**
259 * Determine if any master connection has pending/written changes from this request
260 * @param float|null $age How many seconds ago is "recent" [defaults to LB lag wait timeout]
261 * @return bool
262 */
263 public function hasOrMadeRecentMasterChanges( $age = null );
264
265 /**
266 * Waits for the replica DBs to catch up to the current master position
267 *
268 * Use this when updating very large numbers of rows, as in maintenance scripts,
269 * to avoid causing too much lag. Of course, this is a no-op if there are no replica DBs.
270 *
271 * By default this waits on all DB clusters actually used in this request.
272 * This makes sense when lag being waiting on is caused by the code that does this check.
273 * In that case, setting "ifWritesSince" can avoid the overhead of waiting for clusters
274 * that were not changed since the last wait check. To forcefully wait on a specific cluster
275 * for a given domain, use the 'domain' parameter. To forcefully wait on an "external" cluster,
276 * use the "cluster" parameter.
277 *
278 * Never call this function after a large DB write that is *still* in a transaction.
279 * It only makes sense to call this after the possible lag inducing changes were committed.
280 *
281 * @param array $opts Optional fields that include:
282 * - domain : wait on the load balancer DBs that handles the given domain ID
283 * - cluster : wait on the given external load balancer DBs
284 * - timeout : Max wait time. Default: 60 seconds for CLI, 1 second for web.
285 * - ifWritesSince: Only wait if writes were done since this UNIX timestamp
286 * @return bool True on success, false if a timeout or error occurred while waiting
287 */
288 public function waitForReplication( array $opts = [] );
289
290 /**
291 * Add a callback to be run in every call to waitForReplication() before waiting
292 *
293 * Callbacks must clear any transactions that they start
294 *
295 * @param string $name Callback name
296 * @param callable|null $callback Use null to unset a callback
297 */
298 public function setWaitForReplicationListener( $name, callable $callback = null );
299
300 /**
301 * Get a token asserting that no transaction writes are active
302 *
303 * @param string $fname Caller name (e.g. __METHOD__)
304 * @return mixed A value to pass to commitAndWaitForReplication()
305 */
306 public function getEmptyTransactionTicket( $fname );
307
308 /**
309 * Convenience method for safely running commitMasterChanges()/waitForReplication()
310 *
311 * This will commit and wait unless $ticket indicates it is unsafe to do so
312 *
313 * @param string $fname Caller name (e.g. __METHOD__)
314 * @param mixed $ticket Result of getEmptyTransactionTicket()
315 * @param array $opts Options to waitForReplication()
316 * @return bool True if the wait was successful, false on timeout
317 */
318 public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] );
319
320 /**
321 * @param string $dbName DB master name (e.g. "db1052")
322 * @return float|bool UNIX timestamp when client last touched the DB or false if not recent
323 */
324 public function getChronologyProtectorTouched( $dbName );
325
326 /**
327 * Disable the ChronologyProtector for all load balancers
328 *
329 * This can be called at the start of special API entry points
330 */
331 public function disableChronologyProtection();
332
333 /**
334 * Set a new table prefix for the existing local domain ID for testing
335 *
336 * @param string $prefix
337 * @since 1.33
338 */
339 public function setLocalDomainPrefix( $prefix );
340
341 /**
342 * Close all open database connections on all open load balancers.
343 */
344 public function closeAll();
345
346 /**
347 * @param string $agent Agent name for query profiling
348 */
349 public function setAgentName( $agent );
350
351 /**
352 * Append ?cpPosIndex parameter to a URL for ChronologyProtector purposes if needed
353 *
354 * Note that unlike cookies, this works across domains
355 *
356 * @param string $url
357 * @param int $index Write counter index
358 * @return string
359 */
360 public function appendShutdownCPIndexAsQuery( $url, $index );
361
362 /**
363 * Get the client ID of the ChronologyProtector instance
364 *
365 * @return string Client ID
366 * @since 1.34
367 */
368 public function getChronologyProtectorClientId();
369
370 /**
371 * @param array $info Map of fields, including:
372 * - IPAddress : IP address
373 * - UserAgent : User-Agent HTTP header
374 * - ChronologyProtection : cookie/header value specifying ChronologyProtector usage
375 * - ChronologyPositionIndex: timestamp used to get up-to-date DB positions for the agent
376 */
377 public function setRequestInfo( array $info );
378
379 /**
380 * Make certain table names use their own database, schema, and table prefix
381 * when passed into SQL queries pre-escaped and without a qualified database name
382 *
383 * For example, "user" can be converted to "myschema.mydbname.user" for convenience.
384 * Appearances like `user`, somedb.user, somedb.someschema.user will used literally.
385 *
386 * Calling this twice will completely clear any old table aliases. Also, note that
387 * callers are responsible for making sure the schemas and databases actually exist.
388 *
389 * @param array[] $aliases Map of (table => (dbname, schema, prefix) map)
390 * @since 1.31
391 */
392 public function setTableAliases( array $aliases );
393
394 /**
395 * Convert certain index names to alternative names before querying the DB
396 *
397 * Note that this applies to indexes regardless of the table they belong to.
398 *
399 * This can be employed when an index was renamed X => Y in code, but the new Y-named
400 * indexes were not yet built on all DBs. After all the Y-named ones are added by the DBA,
401 * the aliases can be removed, and then the old X-named indexes dropped.
402 *
403 * @param string[] $aliases
404 * @since 1.31
405 */
406 public function setIndexAliases( array $aliases );
407 }