::DBI:Replicated - merge connect_info from master to replicants
[dbsrgits/DBIx-Class.git] / t / 93storage_replication.t
CommitLineData
e4dc89b3 1use strict;
2use warnings;
3use lib qw(t/lib);
e4dc89b3 4use Test::More;
c4d3fae2 5use Test::Exception;
857d66ca 6use DBICTest;
9901aad7 7use List::Util 'first';
b2e4d522 8use Scalar::Util 'reftype';
8f7986d6 9
86583fa7 10BEGIN {
650c0574 11 eval "use DBIx::Class::Storage::DBI::Replicated; use Test::Moose";
86583fa7 12 plan $@
467799e8 13 ? ( skip_all => "Deps not installed: $@" )
b2e4d522 14 : ( tests => 83 );
26ab719a 15}
16
17use_ok 'DBIx::Class::Storage::DBI::Replicated::Pool';
18use_ok 'DBIx::Class::Storage::DBI::Replicated::Balancer';
19use_ok 'DBIx::Class::Storage::DBI::Replicated::Replicant';
20use_ok 'DBIx::Class::Storage::DBI::Replicated';
0f83441a 21
89cf6a70 22=head1 HOW TO USE
23
24 This is a test of the replicated storage system. This will work in one of
25 two ways, either it was try to fake replication with a couple of SQLite DBs
26 and creative use of copy, or if you define a couple of %ENV vars correctly
27 will try to test those. If you do that, it will assume the setup is properly
28 replicating. Your results may vary, but I have demonstrated this to work with
29 mysql native replication.
30
31=cut
32
33
0f83441a 34## ----------------------------------------------------------------------------
35## Build a class to hold all our required testing data and methods.
36## ----------------------------------------------------------------------------
37
857d66ca 38TESTSCHEMACLASSES: {
2bf79155 39
857d66ca 40 ## --------------------------------------------------------------------- ##
41 ## Create an object to contain your replicated stuff.
42 ## --------------------------------------------------------------------- ##
43
2bf79155 44 package DBIx::Class::DBI::Replicated::TestReplication;
45
46 use DBICTest;
47 use base qw/Class::Accessor::Fast/;
48
857d66ca 49 __PACKAGE__->mk_accessors( qw/schema/ );
2bf79155 50
51 ## Initialize the object
52
53 sub new {
26ab719a 54 my $class = shift @_;
55 my $self = $class->SUPER::new(@_);
2bf79155 56
57 $self->schema( $self->init_schema );
2bf79155 58 return $self;
59 }
60
26ab719a 61 ## Get the Schema and set the replication storage type
2bf79155 62
63 sub init_schema {
f6ace689 64 # current SQLT SQLite producer does not handle DROP TABLE IF EXISTS, trap warnings here
65 local $SIG{__WARN__} = sub { warn @_ unless $_[0] =~ /no such table.+DROP TABLE/ };
66
2bf79155 67 my $class = shift @_;
f6ace689 68
cb6ec758 69 my $schema = DBICTest->init_schema(
bcb3e850 70 sqlite_use_file => 1,
161fb223 71 storage_type=>{
106d5f3b 72 '::DBI::Replicated' => {
73 balancer_type=>'::Random',
17b05c13 74 balancer_args=>{
75 auto_validate_every=>100,
76 },
89cf6a70 77 }
161fb223 78 },
89cf6a70 79 deploy_args=>{
80 add_drop_table => 1,
81 },
82 );
cb6ec758 83
2bf79155 84 return $schema;
85 }
26ab719a 86
857d66ca 87 sub generate_replicant_connect_info {}
88 sub replicate {}
89 sub cleanup {}
90
b2e4d522 91 ## --------------------------------------------------------------------- ##
92 ## Add a connect_info option to test option merging.
93 ## --------------------------------------------------------------------- ##
94 {
95 package DBIx::Class::Storage::DBI::Replicated;
96
97 use Moose;
98
99 __PACKAGE__->meta->make_mutable;
100
101 around connect_info => sub {
102 my ($next, $self, $info) = @_;
103 $info->[3]{master_option} = 1;
104 $self->$next($info);
105 };
106
107 __PACKAGE__->meta->make_immutable;
108
109 no Moose;
110 }
857d66ca 111
112 ## --------------------------------------------------------------------- ##
113 ## Subclass for when you are using SQLite for testing, this provides a fake
114 ## replication support.
115 ## --------------------------------------------------------------------- ##
116
117 package DBIx::Class::DBI::Replicated::TestReplication::SQLite;
118
119 use DBICTest;
120 use File::Copy;
121 use base 'DBIx::Class::DBI::Replicated::TestReplication';
122
123 __PACKAGE__->mk_accessors( qw/master_path slave_paths/ );
124
125 ## Set the mastep path from DBICTest
126
127 sub new {
128 my $class = shift @_;
129 my $self = $class->SUPER::new(@_);
130
131 $self->master_path( DBICTest->_sqlite_dbfilename );
132 $self->slave_paths([
133 "t/var/DBIxClass_slave1.db",
134 "t/var/DBIxClass_slave2.db",
135 ]);
136
137 return $self;
138 }
139
26ab719a 140 ## Return an Array of ArrayRefs where each ArrayRef is suitable to use for
141 ## $storage->connect_info to be used for connecting replicants.
142
143 sub generate_replicant_connect_info {
857d66ca 144 my $self = shift @_;
26ab719a 145 my @dsn = map {
146 "dbi:SQLite:${_}";
147 } @{$self->slave_paths};
148
9901aad7 149 my @connect_infos = map { [$_,'','',{AutoCommit=>1}] } @dsn;
150
151 # try a hashref too
152 my $c = $connect_infos[0];
153 $connect_infos[0] = {
154 dsn => $c->[0],
155 user => $c->[1],
156 password => $c->[2],
157 %{ $c->[3] }
158 };
159
160 @connect_infos
26ab719a 161 }
9901aad7 162
26ab719a 163 ## Do a 'good enough' replication by copying the master dbfile over each of
50336325 164 ## the slave dbfiles. If the master is SQLite we do this, otherwise we
165 ## just do a one second pause to let the slaves catch up.
26ab719a 166
167 sub replicate {
168 my $self = shift @_;
169 foreach my $slave (@{$self->slave_paths}) {
170 copy($self->master_path, $slave);
171 }
172 }
173
174 ## Cleanup after ourselves. Unlink all gthe slave paths.
175
176 sub cleanup {
177 my $self = shift @_;
178 foreach my $slave (@{$self->slave_paths}) {
179 unlink $slave;
180 }
181 }
857d66ca 182
183 ## --------------------------------------------------------------------- ##
184 ## Subclass for when you are setting the databases via custom export vars
185 ## This is for when you have a replicating database setup that you are
186 ## going to test against. You'll need to define the correct $ENV and have
187 ## two slave databases to test against, as well as a replication system
188 ## that will replicate in less than 1 second.
189 ## --------------------------------------------------------------------- ##
190
191 package DBIx::Class::DBI::Replicated::TestReplication::Custom;
192 use base 'DBIx::Class::DBI::Replicated::TestReplication';
193
194 ## Return an Array of ArrayRefs where each ArrayRef is suitable to use for
195 ## $storage->connect_info to be used for connecting replicants.
196
197 sub generate_replicant_connect_info {
198 return (
199 [$ENV{"DBICTEST_SLAVE0_DSN"}, $ENV{"DBICTEST_SLAVE0_DBUSER"}, $ENV{"DBICTEST_SLAVE0_DBPASS"}, {AutoCommit => 1}],
200 [$ENV{"DBICTEST_SLAVE1_DSN"}, $ENV{"DBICTEST_SLAVE1_DBUSER"}, $ENV{"DBICTEST_SLAVE1_DBPASS"}, {AutoCommit => 1}],
201 );
202 }
203
204 ## pause a bit to let the replication catch up
205
206 sub replicate {
207 sleep 1;
208 }
2bf79155 209}
210
211## ----------------------------------------------------------------------------
212## Create an object and run some tests
213## ----------------------------------------------------------------------------
214
26ab719a 215## Thi first bunch of tests are basic, just make sure all the bits are behaving
2bf79155 216
857d66ca 217my $replicated_class = DBICTest->has_custom_dsn ?
218 'DBIx::Class::DBI::Replicated::TestReplication::Custom' :
219 'DBIx::Class::DBI::Replicated::TestReplication::SQLite';
220
221ok my $replicated = $replicated_class->new
222 => 'Created a replication object';
2bf79155 223
26ab719a 224isa_ok $replicated->schema
2bf79155 225 => 'DBIx::Class::Schema';
226
26ab719a 227isa_ok $replicated->schema->storage
228 => 'DBIx::Class::Storage::DBI::Replicated';
229
230ok $replicated->schema->storage->meta
231 => 'has a meta object';
232
233isa_ok $replicated->schema->storage->master
234 => 'DBIx::Class::Storage::DBI';
235
236isa_ok $replicated->schema->storage->pool
237 => 'DBIx::Class::Storage::DBI::Replicated::Pool';
238
17b05c13 239does_ok $replicated->schema->storage->balancer
26ab719a 240 => 'DBIx::Class::Storage::DBI::Replicated::Balancer';
241
242ok my @replicant_connects = $replicated->generate_replicant_connect_info
243 => 'got replication connect information';
244
955a6df6 245ok my @replicated_storages = $replicated->schema->storage->connect_replicants(@replicant_connects)
26ab719a 246 => 'Created some storages suitable for replicants';
6412a592 247
248ok my @all_storages = $replicated->schema->storage->all_storages
249 => '->all_storages';
250
b2e4d522 251is scalar @all_storages
252 ,3
6412a592 253 => 'correct number of ->all_storages';
254
b2e4d522 255is ((grep $_->isa('DBIx::Class::Storage::DBI'), @all_storages)
256 ,3
6412a592 257 => '->all_storages are correct type');
b2e4d522 258
259is ((grep $_->{master_option},
260 grep { (reftype($_)||'') eq 'HASH' }
261 map @{ $_->_connect_info }, @all_storages)
262 ,3
263 => 'connect_info was merged from master to replicants');
9901aad7 264
265my @replicant_names = keys %{ $replicated->schema->storage->replicants };
266
267## Silence warning about not supporting the is_replicating method if using the
268## sqlite dbs.
269$replicated->schema->storage->debugobj->silence(1)
270 if first { m{^t/} } @replicant_names;
271
cb6ec758 272isa_ok $replicated->schema->storage->balancer->current_replicant
9901aad7 273 => 'DBIx::Class::Storage::DBI';
274
275$replicated->schema->storage->debugobj->silence(0);
276
26ab719a 277ok $replicated->schema->storage->pool->has_replicants
278 => 'does have replicants';
279
17b05c13 280is $replicated->schema->storage->pool->num_replicants => 2
26ab719a 281 => 'has two replicants';
282
de5dc9ef 283does_ok $replicated_storages[0]
26ab719a 284 => 'DBIx::Class::Storage::DBI::Replicated::Replicant';
285
de5dc9ef 286does_ok $replicated_storages[1]
26ab719a 287 => 'DBIx::Class::Storage::DBI::Replicated::Replicant';
288
de5dc9ef 289does_ok $replicated->schema->storage->replicants->{$replicant_names[0]}
26ab719a 290 => 'DBIx::Class::Storage::DBI::Replicated::Replicant';
291
de5dc9ef 292does_ok $replicated->schema->storage->replicants->{$replicant_names[1]}
26ab719a 293 => 'DBIx::Class::Storage::DBI::Replicated::Replicant';
294
295## Add some info to the database
296
297$replicated
298 ->schema
299 ->populate('Artist', [
300 [ qw/artistid name/ ],
301 [ 4, "Ozric Tentacles"],
302 ]);
303
304## Make sure all the slaves have the table definitions
305
306$replicated->replicate;
5c1d82d2 307$replicated->schema->storage->replicants->{$replicant_names[0]}->active(1);
308$replicated->schema->storage->replicants->{$replicant_names[1]}->active(1);
9901aad7 309
310## Silence warning about not supporting the is_replicating method if using the
311## sqlite dbs.
312$replicated->schema->storage->debugobj->silence(1)
313 if first { m{^t/} } @replicant_names;
314
f15afa13 315$replicated->schema->storage->pool->validate_replicants;
26ab719a 316
9901aad7 317$replicated->schema->storage->debugobj->silence(0);
318
26ab719a 319## Make sure we can read the data.
320
321ok my $artist1 = $replicated->schema->resultset('Artist')->find(4)
322 => 'Created Result';
323
324isa_ok $artist1
325 => 'DBICTest::Artist';
326
327is $artist1->name, 'Ozric Tentacles'
328 => 'Found expected name for first result';
329
330## Add some new rows that only the master will have This is because
331## we overload any type of write operation so that is must hit the master
332## database.
333
334$replicated
335 ->schema
336 ->populate('Artist', [
337 [ qw/artistid name/ ],
338 [ 5, "Doom's Children"],
339 [ 6, "Dead On Arrival"],
340 [ 7, "Watergate"],
341 ]);
342
26ab719a 343## Make sure all the slaves have the table definitions
344$replicated->replicate;
345
346## Should find some data now
347
348ok my $artist2 = $replicated->schema->resultset('Artist')->find(5)
349 => 'Sync succeed';
350
351isa_ok $artist2
352 => 'DBICTest::Artist';
353
354is $artist2->name, "Doom's Children"
355 => 'Found expected name for first result';
356
357## What happens when we disconnect all the replicants?
358
50336325 359is $replicated->schema->storage->pool->connected_replicants => 2
360 => "both replicants are connected";
361
89cf6a70 362$replicated->schema->storage->replicants->{$replicant_names[0]}->disconnect;
363$replicated->schema->storage->replicants->{$replicant_names[1]}->disconnect;
26ab719a 364
50336325 365is $replicated->schema->storage->pool->connected_replicants => 0
366 => "both replicants are now disconnected";
367
368## All these should pass, since the database should automatically reconnect
369
26ab719a 370ok my $artist3 = $replicated->schema->resultset('Artist')->find(6)
371 => 'Still finding stuff.';
2bf79155 372
26ab719a 373isa_ok $artist3
374 => 'DBICTest::Artist';
2bf79155 375
26ab719a 376is $artist3->name, "Dead On Arrival"
377 => 'Found expected name for first result';
2bf79155 378
50336325 379is $replicated->schema->storage->pool->connected_replicants => 1
13b9e828 380 => "At Least One replicant reconnected to handle the job";
6f6fb437 381
382## What happens when we try to select something that doesn't exist?
383
384ok ! $replicated->schema->resultset('Artist')->find(666)
385 => 'Correctly failed to find something.';
cb6ec758 386
387## test the reliable option
388
389TESTRELIABLE: {
390
391 $replicated->schema->storage->set_reliable_storage;
392
393 ok $replicated->schema->resultset('Artist')->find(2)
394 => 'Read from master 1';
395
396 ok $replicated->schema->resultset('Artist')->find(5)
397 => 'Read from master 2';
398
399 $replicated->schema->storage->set_balanced_storage;
400
401 ok $replicated->schema->resultset('Artist')->find(3)
9c748388 402 => 'Read from replicant';
cb6ec758 403}
404
9c748388 405## Make sure when reliable goes out of scope, we are using replicants again
cb6ec758 406
407ok $replicated->schema->resultset('Artist')->find(1)
408 => 'back to replicant 1.';
409
410ok $replicated->schema->resultset('Artist')->find(2)
411 => 'back to replicant 2.';
2156bbdd 412
106d5f3b 413## set all the replicants to inactive, and make sure the balancer falls back to
414## the master.
415
89cf6a70 416$replicated->schema->storage->replicants->{$replicant_names[0]}->active(0);
417$replicated->schema->storage->replicants->{$replicant_names[1]}->active(0);
9901aad7 418
419## Silence warning about falling back to master.
420$replicated->schema->storage->debugobj->silence(1);
421
106d5f3b 422ok $replicated->schema->resultset('Artist')->find(2)
de5dc9ef 423 => 'Fallback to master';
424
9901aad7 425$replicated->schema->storage->debugobj->silence(0);
426
de5dc9ef 427$replicated->schema->storage->replicants->{$replicant_names[0]}->active(1);
428$replicated->schema->storage->replicants->{$replicant_names[1]}->active(1);
9901aad7 429
430## Silence warning about not supporting the is_replicating method if using the
431## sqlite dbs.
432$replicated->schema->storage->debugobj->silence(1)
433 if first { m{^t/} } @replicant_names;
434
f15afa13 435$replicated->schema->storage->pool->validate_replicants;
de5dc9ef 436
9901aad7 437$replicated->schema->storage->debugobj->silence(0);
438
de5dc9ef 439ok $replicated->schema->resultset('Artist')->find(2)
440 => 'Returned to replicates';
441
442## Getting slave status tests
443
f797e89e 444SKIP: {
445 ## We skip this tests unless you have a custom replicants, since the default
446 ## sqlite based replication tests don't support these functions.
447
17b05c13 448 skip 'Cannot Test Replicant Status on Non Replicating Database', 9
f797e89e 449 unless DBICTest->has_custom_dsn && $ENV{"DBICTEST_SLAVE0_DSN"};
450
451 $replicated->replicate; ## Give the slaves a chance to catchup.
452
453 ok $replicated->schema->storage->replicants->{$replicant_names[0]}->is_replicating
454 => 'Replicants are replicating';
455
456 is $replicated->schema->storage->replicants->{$replicant_names[0]}->lag_behind_master, 0
457 => 'Replicant is zero seconds behind master';
7edf5f1c 458
459 ## Test the validate replicants
460
461 $replicated->schema->storage->pool->validate_replicants;
462
463 is $replicated->schema->storage->pool->active_replicants, 2
464 => 'Still have 2 replicants after validation';
465
466 ## Force the replicants to fail the validate test by required their lag to
467 ## be negative (ie ahead of the master!)
468
469 $replicated->schema->storage->pool->maximum_lag(-10);
470 $replicated->schema->storage->pool->validate_replicants;
471
472 is $replicated->schema->storage->pool->active_replicants, 0
473 => 'No way a replicant be be ahead of the master';
474
475 ## Let's be fair to the replicants again. Let them lag up to 5
476
477 $replicated->schema->storage->pool->maximum_lag(5);
478 $replicated->schema->storage->pool->validate_replicants;
479
480 is $replicated->schema->storage->pool->active_replicants, 2
481 => 'Both replicants in good standing again';
17b05c13 482
483 ## Check auto validate
484
485 is $replicated->schema->storage->balancer->auto_validate_every, 100
486 => "Got the expected value for auto validate";
487
488 ## This will make sure we auto validatge everytime
489 $replicated->schema->storage->balancer->auto_validate_every(0);
490
491 ## set all the replicants to inactive, and make sure the balancer falls back to
492 ## the master.
493
494 $replicated->schema->storage->replicants->{$replicant_names[0]}->active(0);
495 $replicated->schema->storage->replicants->{$replicant_names[1]}->active(0);
496
497 ## Ok, now when we go to run a query, autovalidate SHOULD reconnect
498
499 is $replicated->schema->storage->pool->active_replicants => 0
500 => "both replicants turned off";
501
502 ok $replicated->schema->resultset('Artist')->find(5)
503 => 'replicant reactivated';
504
505 is $replicated->schema->storage->pool->active_replicants => 2
506 => "both replicants reactivated";
f797e89e 507}
508
c4d3fae2 509## Test the reliably callback
510
511ok my $reliably = sub {
512
513 ok $replicated->schema->resultset('Artist')->find(5)
514 => 'replicant reactivated';
515
516} => 'created coderef properly';
517
518$replicated->schema->storage->execute_reliably($reliably);
519
520## Try something with an error
521
522ok my $unreliably = sub {
523
524 ok $replicated->schema->resultset('ArtistXX')->find(5)
525 => 'replicant reactivated';
526
527} => 'created coderef properly';
528
529throws_ok {$replicated->schema->storage->execute_reliably($unreliably)}
ed213e85 530 qr/Can't find source for ArtistXX/
c4d3fae2 531 => 'Bad coderef throws proper error';
532
ed213e85 533## Make sure replication came back
534
535ok $replicated->schema->resultset('Artist')->find(3)
536 => 'replicant reactivated';
537
c4d3fae2 538## make sure transactions are set to execute_reliably
539
540ok my $transaction = sub {
541
ed213e85 542 my $id = shift @_;
543
c4d3fae2 544 $replicated
545 ->schema
546 ->populate('Artist', [
547 [ qw/artistid name/ ],
ed213e85 548 [ $id, "Children of the Grave"],
c4d3fae2 549 ]);
550
64cdad22 551 ok my $result = $replicated->schema->resultset('Artist')->find($id)
552 => 'Found expected artist';
553
554 ok my $more = $replicated->schema->resultset('Artist')->find(1)
555 => 'Found expected artist again';
556
ed213e85 557 return ($result, $more);
c4d3fae2 558
64cdad22 559} => 'Created a coderef properly';
c4d3fae2 560
ed213e85 561## Test the transaction with multi return
562{
563 ok my @return = $replicated->schema->txn_do($transaction, 666)
564 => 'did transaction';
565
566 is $return[0]->id, 666
567 => 'first returned value is correct';
568
569 is $return[1]->id, 1
570 => 'second returned value is correct';
571}
572
573## Test that asking for single return works
574{
575 ok my $return = $replicated->schema->txn_do($transaction, 777)
576 => 'did transaction';
577
578 is $return->id, 777
579 => 'first returned value is correct';
580}
581
582## Test transaction returning a single value
583
584{
585 ok my $result = $replicated->schema->txn_do(sub {
64cdad22 586 ok my $more = $replicated->schema->resultset('Artist')->find(1)
587 => 'found inside a transaction';
ed213e85 588 return $more;
589 }) => 'successfully processed transaction';
590
591 is $result->id, 1
592 => 'Got expected single result from transaction';
593}
c4d3fae2 594
595## Make sure replication came back
596
ed213e85 597ok $replicated->schema->resultset('Artist')->find(1)
c4d3fae2 598 => 'replicant reactivated';
ed213e85 599
600## Test Discard changes
601
602{
603 ok my $artist = $replicated->schema->resultset('Artist')->find(2)
604 => 'got an artist to test discard changes';
605
606 ok $artist->discard_changes
607 => 'properly discard changes';
608}
64cdad22 609
610## Test some edge cases, like trying to do a transaction inside a transaction, etc
611
612{
613 ok my $result = $replicated->schema->txn_do(sub {
614 return $replicated->schema->txn_do(sub {
615 ok my $more = $replicated->schema->resultset('Artist')->find(1)
616 => 'found inside a transaction inside a transaction';
617 return $more;
618 });
619 }) => 'successfully processed transaction';
620
621 is $result->id, 1
622 => 'Got expected single result from transaction';
623}
624
625{
626 ok my $result = $replicated->schema->txn_do(sub {
627 return $replicated->schema->storage->execute_reliably(sub {
628 return $replicated->schema->txn_do(sub {
629 return $replicated->schema->storage->execute_reliably(sub {
630 ok my $more = $replicated->schema->resultset('Artist')->find(1)
631 => 'found inside crazy deep transactions and execute_reliably';
632 return $more;
633 });
634 });
635 });
636 }) => 'successfully processed transaction';
637
638 is $result->id, 1
639 => 'Got expected single result from transaction';
640}
2ce6e9a6 641
7e38d850 642## Test the force_pool resultset attribute.
bbafcf26 643
644{
645 ok my $artist_rs = $replicated->schema->resultset('Artist')
646 => 'got artist resultset';
647
7e38d850 648 ## Turn on Forced Pool Storage
649 ok my $reliable_artist_rs = $artist_rs->search(undef, {force_pool=>'master'})
650 => 'Created a resultset using force_pool storage';
bbafcf26 651
652 ok my $artist = $reliable_artist_rs->find(2)
7e38d850 653 => 'got an artist result via force_pool storage';
bbafcf26 654}
655
0f83441a 656## Delete the old database files
50336325 657$replicated->cleanup;