MediaWiki REL1_32
LBFactoryTest.php
Go to the documentation of this file.
1<?php
34
42
47 public function testGetLBFactoryClass( $expected, $deprecated ) {
48 $mockDB = $this->getMockBuilder( DatabaseMysqli::class )
49 ->disableOriginalConstructor()
50 ->getMock();
51
52 $config = [
53 'class' => $deprecated,
54 'connection' => $mockDB,
55 # Various other parameters required:
56 'sectionsByDB' => [],
57 'sectionLoads' => [],
58 'serverTemplate' => [],
59 ];
60
61 $this->hideDeprecated( '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details' );
63
64 $this->assertEquals( $expected, $result );
65 }
66
67 public function getLBFactoryClassProvider() {
68 return [
69 # Format: new class, old class
70 [ Wikimedia\Rdbms\LBFactorySimple::class, 'LBFactory_Simple' ],
71 [ Wikimedia\Rdbms\LBFactorySingle::class, 'LBFactory_Single' ],
72 [ Wikimedia\Rdbms\LBFactoryMulti::class, 'LBFactory_Multi' ],
73 [ Wikimedia\Rdbms\LBFactorySimple::class, 'LBFactorySimple' ],
74 [ Wikimedia\Rdbms\LBFactorySingle::class, 'LBFactorySingle' ],
75 [ Wikimedia\Rdbms\LBFactoryMulti::class, 'LBFactoryMulti' ],
76 ];
77 }
78
83 public function testLBFactorySimpleServer() {
85
86 $servers = [
87 [
88 'host' => $wgDBserver,
89 'dbname' => $wgDBname,
90 'user' => $wgDBuser,
91 'password' => $wgDBpassword,
92 'type' => $wgDBtype,
93 'dbDirectory' => $wgSQLiteDataDir,
94 'load' => 0,
95 'flags' => DBO_TRX // REPEATABLE-READ for consistency
96 ],
97 ];
98
99 $factory = new LBFactorySimple( [ 'servers' => $servers ] );
100 $lb = $factory->getMainLB();
101
102 $dbw = $lb->getConnection( DB_MASTER );
103 $this->assertTrue( $dbw->getLBInfo( 'master' ), 'master shows as master' );
104
105 $dbr = $lb->getConnection( DB_REPLICA );
106 $this->assertTrue( $dbr->getLBInfo( 'master' ), 'DB_REPLICA also gets the master' );
107
108 $this->assertSame( 'my_test_wiki', $factory->resolveDomainID( 'my_test_wiki' ) );
109 $this->assertSame( $factory->getLocalDomainID(), $factory->resolveDomainID( false ) );
110
111 $factory->shutdown();
112 $lb->closeAll();
113 }
114
115 public function testLBFactorySimpleServers() {
117
118 $servers = [
119 [ // master
120 'host' => $wgDBserver,
121 'dbname' => $wgDBname,
122 'user' => $wgDBuser,
123 'password' => $wgDBpassword,
124 'type' => $wgDBtype,
125 'dbDirectory' => $wgSQLiteDataDir,
126 'load' => 0,
127 'flags' => DBO_TRX // REPEATABLE-READ for consistency
128 ],
129 [ // emulated slave
130 'host' => $wgDBserver,
131 'dbname' => $wgDBname,
132 'user' => $wgDBuser,
133 'password' => $wgDBpassword,
134 'type' => $wgDBtype,
135 'dbDirectory' => $wgSQLiteDataDir,
136 'load' => 100,
137 'flags' => DBO_TRX // REPEATABLE-READ for consistency
138 ]
139 ];
140
141 $factory = new LBFactorySimple( [
142 'servers' => $servers,
143 'loadMonitorClass' => LoadMonitorNull::class
144 ] );
145 $lb = $factory->getMainLB();
146
147 $dbw = $lb->getConnection( DB_MASTER );
148 $this->assertTrue( $dbw->getLBInfo( 'master' ), 'master shows as master' );
149 $this->assertEquals(
150 ( $wgDBserver != '' ) ? $wgDBserver : 'localhost',
151 $dbw->getLBInfo( 'clusterMasterHost' ),
152 'cluster master set' );
153
154 $dbr = $lb->getConnection( DB_REPLICA );
155 $this->assertTrue( $dbr->getLBInfo( 'replica' ), 'slave shows as slave' );
156 $this->assertEquals(
157 ( $wgDBserver != '' ) ? $wgDBserver : 'localhost',
158 $dbr->getLBInfo( 'clusterMasterHost' ),
159 'cluster master set' );
160
161 $factory->shutdown();
162 $lb->closeAll();
163 }
164
165 public function testLBFactoryMultiConns() {
166 $factory = $this->newLBFactoryMultiLBs();
167
168 $dbw = $factory->getMainLB()->getConnection( DB_MASTER );
169 $this->assertTrue( $dbw->getLBInfo( 'master' ), 'master shows as master' );
170
171 $dbr = $factory->getMainLB()->getConnection( DB_REPLICA );
172 $this->assertTrue( $dbr->getLBInfo( 'replica' ), 'slave shows as slave' );
173
174 // Destructor should trigger without round stage errors
175 unset( $factory );
176 }
177
179 $called = 0;
180 $countLBsFunc = function ( LBFactoryMulti $factory ) {
181 $count = 0;
182 $factory->forEachLB( function () use ( &$count ) {
183 ++$count;
184 } );
185
186 return $count;
187 };
188
189 $factory = $this->newLBFactoryMultiLBs();
190 $this->assertEquals( 0, $countLBsFunc( $factory ) );
191 $dbw = $factory->getMainLB()->getConnection( DB_MASTER );
192 $this->assertEquals( 1, $countLBsFunc( $factory ) );
193 // Test that LoadBalancer instances made during pre-commit callbacks in do not
194 // throw DBTransactionError due to transaction ROUND_* stages being mismatched.
195 $factory->beginMasterChanges( __METHOD__ );
196 $dbw->onTransactionPreCommitOrIdle( function () use ( $factory, &$called ) {
197 ++$called;
198 // Trigger s1 LoadBalancer instantiation during "finalize" stage.
199 // There is no s1wiki DB to select so it is not in getConnection(),
200 // but this fools getMainLB() at least.
201 $factory->getMainLB( 's1wiki' )->getConnection( DB_MASTER );
202 } );
203 $factory->commitMasterChanges( __METHOD__ );
204 $this->assertEquals( 1, $called );
205 $this->assertEquals( 2, $countLBsFunc( $factory ) );
206 $factory->shutdown();
207 $factory->closeAll();
208
209 $called = 0;
210 $factory = $this->newLBFactoryMultiLBs();
211 $this->assertEquals( 0, $countLBsFunc( $factory ) );
212 $dbw = $factory->getMainLB()->getConnection( DB_MASTER );
213 $this->assertEquals( 1, $countLBsFunc( $factory ) );
214 // Test that LoadBalancer instances made during pre-commit callbacks in do not
215 // throw DBTransactionError due to transaction ROUND_* stages being mismatched.hrow
216 // DBTransactionError due to transaction ROUND_* stages being mismatched.
217 $factory->beginMasterChanges( __METHOD__ );
218 $dbw->query( "SELECT 1 as t", __METHOD__ );
219 $dbw->onTransactionResolution( function () use ( $factory, &$called ) {
220 ++$called;
221 // Trigger s1 LoadBalancer instantiation during "finalize" stage.
222 // There is no s1wiki DB to select so it is not in getConnection(),
223 // but this fools getMainLB() at least.
224 $factory->getMainLB( 's1wiki' )->getConnection( DB_MASTER );
225 } );
226 $factory->commitMasterChanges( __METHOD__ );
227 $this->assertEquals( 1, $called );
228 $this->assertEquals( 2, $countLBsFunc( $factory ) );
229 $factory->shutdown();
230 $factory->closeAll();
231
232 $factory = $this->newLBFactoryMultiLBs();
233 $dbw = $factory->getMainLB()->getConnection( DB_MASTER );
234 // DBTransactionError should not be thrown
235 $ran = 0;
236 $dbw->onTransactionPreCommitOrIdle( function () use ( &$ran ) {
237 ++$ran;
238 } );
239 $factory->commitAll( __METHOD__ );
240 $this->assertEquals( 1, $ran );
241
242 $factory->shutdown();
243 $factory->closeAll();
244 }
245
246 private function newLBFactoryMultiLBs() {
248
249 return new LBFactoryMulti( [
250 'sectionsByDB' => [
251 's1wiki' => 's1',
252 ],
253 'sectionLoads' => [
254 's1' => [
255 'test-db3' => 0,
256 'test-db4' => 100,
257 ],
258 'DEFAULT' => [
259 'test-db1' => 0,
260 'test-db2' => 100,
261 ]
262 ],
263 'serverTemplate' => [
264 'dbname' => $wgDBname,
265 'user' => $wgDBuser,
266 'password' => $wgDBpassword,
267 'type' => $wgDBtype,
268 'dbDirectory' => $wgSQLiteDataDir,
269 'flags' => DBO_DEFAULT
270 ],
271 'hostsByName' => [
272 'test-db1' => $wgDBserver,
273 'test-db2' => $wgDBserver,
274 'test-db3' => $wgDBserver,
275 'test-db4' => $wgDBserver
276 ],
277 'loadMonitorClass' => LoadMonitorNull::class
278 ] );
279 }
280
284 public function testChronologyProtector() {
285 $now = microtime( true );
286
287 // (a) First HTTP request
288 $m1Pos = new MySQLMasterPos( 'db1034-bin.000976/843431247', $now );
289 $m2Pos = new MySQLMasterPos( 'db1064-bin.002400/794074907', $now );
290
291 // Master DB 1
292 $mockDB1 = $this->getMockBuilder( DatabaseMysqli::class )
293 ->disableOriginalConstructor()
294 ->getMock();
295 $mockDB1->method( 'writesOrCallbacksPending' )->willReturn( true );
296 $mockDB1->method( 'lastDoneWrites' )->willReturn( $now );
297 $mockDB1->method( 'getMasterPos' )->willReturn( $m1Pos );
298 // Load balancer for master DB 1
299 $lb1 = $this->getMockBuilder( LoadBalancer::class )
300 ->disableOriginalConstructor()
301 ->getMock();
302 $lb1->method( 'getConnection' )->willReturn( $mockDB1 );
303 $lb1->method( 'getServerCount' )->willReturn( 2 );
304 $lb1->method( 'getAnyOpenConnection' )->willReturn( $mockDB1 );
305 $lb1->method( 'hasOrMadeRecentMasterChanges' )->will( $this->returnCallback(
306 function () use ( $mockDB1 ) {
307 $p = 0;
308 $p |= call_user_func( [ $mockDB1, 'writesOrCallbacksPending' ] );
309 $p |= call_user_func( [ $mockDB1, 'lastDoneWrites' ] );
310
311 return (bool)$p;
312 }
313 ) );
314 $lb1->method( 'getMasterPos' )->willReturn( $m1Pos );
315 $lb1->method( 'getServerName' )->with( 0 )->willReturn( 'master1' );
316 // Master DB 2
317 $mockDB2 = $this->getMockBuilder( DatabaseMysqli::class )
318 ->disableOriginalConstructor()
319 ->getMock();
320 $mockDB2->method( 'writesOrCallbacksPending' )->willReturn( true );
321 $mockDB2->method( 'lastDoneWrites' )->willReturn( $now );
322 $mockDB2->method( 'getMasterPos' )->willReturn( $m2Pos );
323 // Load balancer for master DB 2
324 $lb2 = $this->getMockBuilder( LoadBalancer::class )
325 ->disableOriginalConstructor()
326 ->getMock();
327 $lb2->method( 'getConnection' )->willReturn( $mockDB2 );
328 $lb2->method( 'getServerCount' )->willReturn( 2 );
329 $lb2->method( 'getAnyOpenConnection' )->willReturn( $mockDB2 );
330 $lb2->method( 'hasOrMadeRecentMasterChanges' )->will( $this->returnCallback(
331 function () use ( $mockDB2 ) {
332 $p = 0;
333 $p |= call_user_func( [ $mockDB2, 'writesOrCallbacksPending' ] );
334 $p |= call_user_func( [ $mockDB2, 'lastDoneWrites' ] );
335
336 return (bool)$p;
337 }
338 ) );
339 $lb2->method( 'getMasterPos' )->willReturn( $m2Pos );
340 $lb2->method( 'getServerName' )->with( 0 )->willReturn( 'master2' );
341
342 $bag = new HashBagOStuff();
343 $cp = new ChronologyProtector(
344 $bag,
345 [
346 'ip' => '127.0.0.1',
347 'agent' => "Totally-Not-FireFox"
348 ]
349 );
350
351 $mockDB1->expects( $this->exactly( 1 ) )->method( 'writesOrCallbacksPending' );
352 $mockDB1->expects( $this->exactly( 1 ) )->method( 'lastDoneWrites' );
353 $mockDB2->expects( $this->exactly( 1 ) )->method( 'writesOrCallbacksPending' );
354 $mockDB2->expects( $this->exactly( 1 ) )->method( 'lastDoneWrites' );
355
356 // Nothing to wait for on first HTTP request start
357 $cp->initLB( $lb1 );
358 $cp->initLB( $lb2 );
359 // Record positions in stash on first HTTP request end
360 $cp->shutdownLB( $lb1 );
361 $cp->shutdownLB( $lb2 );
362 $cpIndex = null;
363 $cp->shutdown( null, 'sync', $cpIndex );
364
365 $this->assertEquals( 1, $cpIndex, "CP write index set" );
366
367 // (b) Second HTTP request
368
369 // Load balancer for master DB 1
370 $lb1 = $this->getMockBuilder( LoadBalancer::class )
371 ->disableOriginalConstructor()
372 ->getMock();
373 $lb1->method( 'getServerCount' )->willReturn( 2 );
374 $lb1->method( 'getServerName' )->with( 0 )->willReturn( 'master1' );
375 $lb1->expects( $this->once() )
376 ->method( 'waitFor' )->with( $this->equalTo( $m1Pos ) );
377 // Load balancer for master DB 2
378 $lb2 = $this->getMockBuilder( LoadBalancer::class )
379 ->disableOriginalConstructor()
380 ->getMock();
381 $lb2->method( 'getServerCount' )->willReturn( 2 );
382 $lb2->method( 'getServerName' )->with( 0 )->willReturn( 'master2' );
383 $lb2->expects( $this->once() )
384 ->method( 'waitFor' )->with( $this->equalTo( $m2Pos ) );
385
386 $cp = new ChronologyProtector(
387 $bag,
388 [
389 'ip' => '127.0.0.1',
390 'agent' => "Totally-Not-FireFox"
391 ],
392 $cpIndex
393 );
394
395 // Wait for last positions to be reached on second HTTP request start
396 $cp->initLB( $lb1 );
397 $cp->initLB( $lb2 );
398 // Shutdown (nothing to record)
399 $cp->shutdownLB( $lb1 );
400 $cp->shutdownLB( $lb2 );
401 $cpIndex = null;
402 $cp->shutdown( null, 'sync', $cpIndex );
403
404 $this->assertEquals( null, $cpIndex, "CP write index retained" );
405
406 $this->assertEquals( '45e93a9c215c031d38b7c42d8e4700ca', $cp->getClientId() );
407 }
408
409 private function newLBFactoryMulti( array $baseOverride = [], array $serverOverride = [] ) {
411 global $wgSQLiteDataDir;
412
413 return new LBFactoryMulti( $baseOverride + [
414 'sectionsByDB' => [],
415 'sectionLoads' => [
416 'DEFAULT' => [
417 'test-db1' => 1,
418 ],
419 ],
420 'serverTemplate' => $serverOverride + [
421 'dbname' => $wgDBname,
422 'tablePrefix' => $wgDBprefix,
423 'user' => $wgDBuser,
424 'password' => $wgDBpassword,
425 'type' => $wgDBtype,
426 'dbDirectory' => $wgSQLiteDataDir,
427 'flags' => DBO_DEFAULT
428 ],
429 'hostsByName' => [
430 'test-db1' => $wgDBserver,
431 ],
432 'loadMonitorClass' => LoadMonitorNull::class,
433 'localDomain' => new DatabaseDomain( $wgDBname, null, $wgDBprefix ),
434 'agent' => 'MW-UNIT-TESTS'
435 ] );
436 }
437
438 public function testNiceDomains() {
439 global $wgDBname;
440
441 if ( wfGetDB( DB_MASTER )->databasesAreIndependent() ) {
442 self::markTestSkipped( "Skipping tests about selecting DBs: not applicable" );
443 return;
444 }
445
446 $factory = $this->newLBFactoryMulti(
447 [],
448 []
449 );
450 $lb = $factory->getMainLB();
451
452 $db = $lb->getConnectionRef( DB_MASTER );
453 $this->assertEquals(
454 wfWikiID(),
456 );
457 unset( $db );
458
460 $db = $lb->getConnection( DB_MASTER, [], '' );
461
462 $this->assertEquals(
463 '',
464 $db->getDomainId(),
465 'Null domain ID handle used'
466 );
467 $this->assertEquals(
468 '',
469 $db->getDBname(),
470 'Null domain ID handle used'
471 );
472 $this->assertEquals(
473 '',
474 $db->tablePrefix(),
475 'Main domain ID handle used; prefix is empty though'
476 );
477 $this->assertEquals(
478 $this->quoteTable( $db, 'page' ),
479 $db->tableName( 'page' ),
480 "Correct full table name"
481 );
482 $this->assertEquals(
483 $this->quoteTable( $db, $wgDBname ) . '.' . $this->quoteTable( $db, 'page' ),
484 $db->tableName( "$wgDBname.page" ),
485 "Correct full table name"
486 );
487 $this->assertEquals(
488 $this->quoteTable( $db, 'nice_db' ) . '.' . $this->quoteTable( $db, 'page' ),
489 $db->tableName( 'nice_db.page' ),
490 "Correct full table name"
491 );
492
493 $lb->reuseConnection( $db ); // don't care
494
495 $db = $lb->getConnection( DB_MASTER ); // local domain connection
496 $factory->setDomainPrefix( 'my_' );
497
498 $this->assertEquals( $wgDBname, $db->getDBname() );
499 $this->assertEquals(
500 "$wgDBname-my_",
502 );
503 $this->assertEquals(
504 $this->quoteTable( $db, 'my_page' ),
505 $db->tableName( 'page' ),
506 "Correct full table name"
507 );
508 $this->assertEquals(
509 $this->quoteTable( $db, 'other_nice_db' ) . '.' . $this->quoteTable( $db, 'page' ),
510 $db->tableName( 'other_nice_db.page' ),
511 "Correct full table name"
512 );
513
514 $factory->closeAll();
515 $factory->destroy();
516 }
517
518 public function testTrickyDomain() {
519 global $wgDBname;
520
521 if ( wfGetDB( DB_MASTER )->databasesAreIndependent() ) {
522 self::markTestSkipped( "Skipping tests about selecting DBs: not applicable" );
523 return;
524 }
525
526 $dbname = 'unittest-domain'; // explodes if DB is selected
527 $factory = $this->newLBFactoryMulti(
528 [ 'localDomain' => ( new DatabaseDomain( $dbname, null, '' ) )->getId() ],
529 [
530 'dbName' => 'do_not_select_me' // explodes if DB is selected
531 ]
532 );
533 $lb = $factory->getMainLB();
535 $db = $lb->getConnection( DB_MASTER, [], '' );
536
537 $this->assertEquals( '', $db->getDomainID(), "Null domain used" );
538
539 $this->assertEquals(
540 $this->quoteTable( $db, 'page' ),
541 $db->tableName( 'page' ),
542 "Correct full table name"
543 );
544
545 $this->assertEquals(
546 $this->quoteTable( $db, $dbname ) . '.' . $this->quoteTable( $db, 'page' ),
547 $db->tableName( "$dbname.page" ),
548 "Correct full table name"
549 );
550
551 $this->assertEquals(
552 $this->quoteTable( $db, 'nice_db' ) . '.' . $this->quoteTable( $db, 'page' ),
553 $db->tableName( 'nice_db.page' ),
554 "Correct full table name"
555 );
556
557 $lb->reuseConnection( $db ); // don't care
558
559 $factory->setDomainPrefix( 'my_' );
560 $db = $lb->getConnection( DB_MASTER, [], "$wgDBname-my_" );
561
562 $this->assertEquals(
563 $this->quoteTable( $db, 'my_page' ),
564 $db->tableName( 'page' ),
565 "Correct full table name"
566 );
567 $this->assertEquals(
568 $this->quoteTable( $db, 'other_nice_db' ) . '.' . $this->quoteTable( $db, 'page' ),
569 $db->tableName( 'other_nice_db.page' ),
570 "Correct full table name"
571 );
572 $this->assertEquals(
573 $this->quoteTable( $db, 'garbage-db' ) . '.' . $this->quoteTable( $db, 'page' ),
574 $db->tableName( 'garbage-db.page' ),
575 "Correct full table name"
576 );
577
578 $lb->reuseConnection( $db ); // don't care
579
580 $factory->closeAll();
581 $factory->destroy();
582 }
583
584 public function testInvalidSelectDB() {
585 // FIXME: fails under sqlite
586 $this->markTestSkippedIfDbType( 'sqlite' );
587 $dbname = 'unittest-domain'; // explodes if DB is selected
588 $factory = $this->newLBFactoryMulti(
589 [ 'localDomain' => ( new DatabaseDomain( $dbname, null, '' ) )->getId() ],
590 [
591 'dbName' => 'do_not_select_me' // explodes if DB is selected
592 ]
593 );
594 $lb = $factory->getMainLB();
596 $db = $lb->getConnection( DB_MASTER, [], '' );
597
598 if ( $db->getType() === 'sqlite' ) {
599 $this->assertFalse( $db->selectDB( 'garbage-db' ) );
600 } elseif ( $db->databasesAreIndependent() ) {
601 try {
602 $e = null;
603 $db->selectDB( 'garbage-db' );
604 } catch ( \Wikimedia\Rdbms\DBConnectionError $e ) {
605 // expected
606 }
607 $this->assertInstanceOf( \Wikimedia\Rdbms\DBConnectionError::class, $e );
608 $this->assertFalse( $db->isOpen() );
609 } else {
610 \Wikimedia\suppressWarnings();
611 try {
612 $this->assertFalse( $db->selectDB( 'garbage-db' ) );
613 $this->fail( "No error thrown." );
614 } catch ( \Wikimedia\Rdbms\DBExpectedError $e ) {
615 $this->assertEquals(
616 "Could not select database 'garbage-db'.",
617 $e->getMessage()
618 );
619 }
620 \Wikimedia\restoreWarnings();
621 }
622 }
623
624 public function testRedefineLocalDomain() {
625 global $wgDBname;
626
627 if ( wfGetDB( DB_MASTER )->databasesAreIndependent() ) {
628 self::markTestSkipped( "Skipping tests about selecting DBs: not applicable" );
629 return;
630 }
631
632 $factory = $this->newLBFactoryMulti(
633 [],
634 []
635 );
636 $lb = $factory->getMainLB();
637
638 $conn1 = $lb->getConnectionRef( DB_MASTER );
639 $this->assertEquals(
640 wfWikiID(),
641 $conn1->getDomainID()
642 );
643 unset( $conn1 );
644
645 $factory->redefineLocalDomain( 'somedb-prefix' );
646 $this->assertEquals( 'somedb-prefix', $factory->getLocalDomainID() );
647
648 $domain = new DatabaseDomain( $wgDBname, null, 'pref' );
649 $factory->redefineLocalDomain( $domain );
650
651 $n = 0;
652 $lb->forEachOpenConnection( function () use ( &$n ) {
653 ++$n;
654 } );
655 $this->assertEquals( 0, $n, "Connections closed" );
656
657 $conn2 = $lb->getConnectionRef( DB_MASTER );
658 $this->assertEquals(
659 $domain->getId(),
660 $conn2->getDomainID()
661 );
662 unset( $conn2 );
663
664 $factory->closeAll();
665 $factory->destroy();
666 }
667
668 private function quoteTable( Database $db, $table ) {
669 if ( $db->getType() === 'sqlite' ) {
670 return $table;
671 } else {
672 return $db->addIdentifierQuotes( $table );
673 }
674 }
675
680 public function testCPPosIndexCookieValues() {
681 $time = 1526522031;
682 $agentId = md5( 'Ramsey\'s Loyal Presa Canario' );
683
684 $this->assertEquals(
685 '3@542#c47dcfb0566e7d7bc110a6128a45c93a',
686 LBFactory::makeCookieValueFromCPIndex( 3, 542, $agentId )
687 );
688
689 $lbFactory = $this->newLBFactoryMulti();
690 $lbFactory->setRequestInfo( [ 'IPAddress' => '10.64.24.52', 'UserAgent' => 'meow' ] );
691 $this->assertEquals(
692 '1@542#c47dcfb0566e7d7bc110a6128a45c93a',
693 LBFactory::makeCookieValueFromCPIndex( 1, 542, $agentId )
694 );
695
696 $this->assertSame(
697 null,
698 LBFactory::getCPInfoFromCookieValue( "5#$agentId", $time - 10 )['index'],
699 'No time set'
700 );
701 $this->assertSame(
702 null,
703 LBFactory::getCPInfoFromCookieValue( "5@$time", $time - 10 )['index'],
704 'No agent set'
705 );
706 $this->assertSame(
707 null,
708 LBFactory::getCPInfoFromCookieValue( "0@$time#$agentId", $time - 10 )['index'],
709 'Bad index'
710 );
711
712 $this->assertSame(
713 2,
714 LBFactory::getCPInfoFromCookieValue( "2@$time#$agentId", $time - 10 )['index'],
715 'Fresh'
716 );
717 $this->assertSame(
718 2,
719 LBFactory::getCPInfoFromCookieValue( "2@$time#$agentId", $time + 9 - 10 )['index'],
720 'Almost stale'
721 );
722 $this->assertSame(
723 null,
724 LBFactory::getCPInfoFromCookieValue( "0@$time#$agentId", $time + 9 - 10 )['index'],
725 'Almost stale; bad index'
726 );
727 $this->assertSame(
728 null,
729 LBFactory::getCPInfoFromCookieValue( "2@$time#$agentId", $time + 11 - 10 )['index'],
730 'Stale'
731 );
732
733 $this->assertSame(
734 $agentId,
735 LBFactory::getCPInfoFromCookieValue( "5@$time#$agentId", $time - 10 )['clientId'],
736 'Live (client ID)'
737 );
738 $this->assertSame(
739 null,
740 LBFactory::getCPInfoFromCookieValue( "5@$time#$agentId", $time + 11 - 10 )['clientId'],
741 'Stale (client ID)'
742 );
743 }
744}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
$wgDBprefix
Table name prefix.
$wgDBuser
Database username.
$wgSQLiteDataDir
To override default SQLite data directory ($docroot/../data)
$wgDBtype
Database type.
$wgDBserver
Database host name or IP address.
$wgDBpassword
Database user's password.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
Simple store for keeping values in an associative array for the current process.
Database \Wikimedia\Rdbms\LBFactory \Wikimedia\Rdbms\LBFactorySimple \Wikimedia\Rdbms\LBFactoryMulti.
quoteTable(Database $db, $table)
testChronologyProtector()
\Wikimedia\Rdbms\ChronologyProtector
testLBFactorySimpleServer()
\Wikimedia\Rdbms\LBFactory::getLocalDomainID() \Wikimedia\Rdbms\LBFactory::resolveDomainID()
newLBFactoryMulti(array $baseOverride=[], array $serverOverride=[])
testGetLBFactoryClass( $expected, $deprecated)
MWLBFactory::getLBFactoryClass() getLBFactoryClassProvider.
testCPPosIndexCookieValues()
\Wikimedia\Rdbms\LBFactory::makeCookieValueFromCPIndex() \Wikimedia\Rdbms\LBFactory::getCPInfoFromCoo...
testLBFactoryMultiRoundCallbacks()
static getLBFactoryClass(array $config)
Returns the LBFactory class to use and the load balancer configuration.
Database $db
Primary database.
markTestSkippedIfDbType( $type)
Skip the test if using the specified database type.
hideDeprecated( $function)
Don't throw a warning if $function is deprecated and called later.
$called
$called tracks whether the setUp and tearDown method has been called.
Class for ensuring a consistent ordering of events as seen by the user, despite replication.
Class to handle database/prefix specification for IDatabase domains.
Database abstraction object for PHP extension mysqli.
selectDB( $db)
Change the current database.
tablePrefix( $prefix=null)
Get/set the table prefix.
Definition Database.php:595
getDomainID()
Return the currently selected domain ID.
Definition Database.php:835
databasesAreIndependent()
Returns true if DBs are assumed to be on potentially different servers.
tableName( $name, $format='quoted')
Format a table name ready for use in constructing an SQL query.
addIdentifierQuotes( $s)
Quotes an identifier using backticks or "double quotes" depending on the database type.
isOpen()
Is a connection to the database open?
Definition Database.php:783
getDBname()
Get the current DB name.
A multi-database, multi-master factory for Wikimedia and similar installations.
A simple single-master LBFactory that gets its configuration from the b/c globals.
An interface for generating database load balancers.
Definition LBFactory.php:39
Database connection, tracking, load balancing, and transaction manager for a cluster.
DBMasterPos class for MySQL/MariaDB.
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition hooks.txt:1841
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED since 1.16! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition hooks.txt:2042
returning false will NOT prevent logging $e
Definition hooks.txt:2226
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:37
getType()
Get the type of the DBMS, as it appears in $wgDBtype.
controlled by the following MediaWiki still creates a BagOStuff but calls it to it are no ops If the cache daemon can t be it should also disable itself fairly $wgDBname
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
This program is free software; you can redistribute it and/or modify it under the terms of the GNU Ge...
const DB_REPLICA
Definition defines.php:25
const DB_MASTER
Definition defines.php:26
const DBO_DEFAULT
Definition defines.php:13
const DBO_TRX
Definition defines.php:12