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