Port replicated storage from MXAH to native traits.
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Storage / DBI / Replicated.pm
1 package DBIx::Class::Storage::DBI::Replicated;
2
3 BEGIN {
4   use Carp::Clan qw/^DBIx::Class/;
5
6   ## Modules required for Replication support not required for general DBIC
7   ## use, so we explicitly test for these.
8
9   my %replication_required = (
10     'Moose' => '0.90',
11     'MooseX::Types' => '0.16',
12     'namespace::clean' => '0.11',
13     'Hash::Merge' => '0.11'
14   );
15
16   my @didnt_load;
17
18   for my $module (keys %replication_required) {
19     eval "use $module $replication_required{$module}";
20     push @didnt_load, "$module $replication_required{$module}"
21       if $@;
22   }
23
24   croak("@{[ join ', ', @didnt_load ]} are missing and are required for Replication")
25     if @didnt_load;
26 }
27
28 use Moose;
29 use DBIx::Class::Storage::DBI;
30 use DBIx::Class::Storage::DBI::Replicated::Pool;
31 use DBIx::Class::Storage::DBI::Replicated::Balancer;
32 use DBIx::Class::Storage::DBI::Replicated::Types qw/BalancerClassNamePart DBICSchema DBICStorageDBI/;
33 use MooseX::Types::Moose qw/ClassName HashRef Object/;
34 use Scalar::Util 'reftype';
35 use Hash::Merge 'merge';
36
37 use namespace::clean -except => 'meta';
38
39 =head1 NAME
40
41 DBIx::Class::Storage::DBI::Replicated - BETA Replicated database support
42
43 =head1 SYNOPSIS
44
45 The Following example shows how to change an existing $schema to a replicated
46 storage type, add some replicated (readonly) databases, and perform reporting
47 tasks.
48
49 You should set the 'storage_type attribute to a replicated type.  You should
50 also define your arguments, such as which balancer you want and any arguments
51 that the Pool object should get.
52
53   $schema->storage_type( ['::DBI::Replicated', {balancer=>'::Random'}] );
54
55 Next, you need to add in the Replicants.  Basically this is an array of 
56 arrayrefs, where each arrayref is database connect information.  Think of these
57 arguments as what you'd pass to the 'normal' $schema->connect method.
58
59   $schema->storage->connect_replicants(
60     [$dsn1, $user, $pass, \%opts],
61     [$dsn2, $user, $pass, \%opts],
62     [$dsn3, $user, $pass, \%opts],
63   );
64
65 Now, just use the $schema as you normally would.  Automatically all reads will
66 be delegated to the replicants, while writes to the master.
67
68   $schema->resultset('Source')->search({name=>'etc'});
69
70 You can force a given query to use a particular storage using the search
71 attribute 'force_pool'.  For example:
72
73   my $RS = $schema->resultset('Source')->search(undef, {force_pool=>'master'});
74
75 Now $RS will force everything (both reads and writes) to use whatever was setup
76 as the master storage.  'master' is hardcoded to always point to the Master, 
77 but you can also use any Replicant name.  Please see:
78 L<DBIx::Class::Storage::DBI::Replicated::Pool> and the replicants attribute for more.
79
80 Also see transactions and L</execute_reliably> for alternative ways to
81 force read traffic to the master.  In general, you should wrap your statements
82 in a transaction when you are reading and writing to the same tables at the
83 same time, since your replicants will often lag a bit behind the master.
84
85 See L<DBIx::Class::Storage::DBI::Replicated::Instructions> for more help and
86 walkthroughs.
87
88 =head1 DESCRIPTION
89
90 Warning: This class is marked BETA.  This has been running a production
91 website using MySQL native replication as its backend and we have some decent
92 test coverage but the code hasn't yet been stressed by a variety of databases.
93 Individual DB's may have quirks we are not aware of.  Please use this in first
94 development and pass along your experiences/bug fixes.
95
96 This class implements replicated data store for DBI. Currently you can define
97 one master and numerous slave database connections. All write-type queries
98 (INSERT, UPDATE, DELETE and even LAST_INSERT_ID) are routed to master
99 database, all read-type queries (SELECTs) go to the slave database.
100
101 Basically, any method request that L<DBIx::Class::Storage::DBI> would normally
102 handle gets delegated to one of the two attributes: L</read_handler> or to
103 L</write_handler>.  Additionally, some methods need to be distributed
104 to all existing storages.  This way our storage class is a drop in replacement
105 for L<DBIx::Class::Storage::DBI>.
106
107 Read traffic is spread across the replicants (slaves) occuring to a user
108 selected algorithm.  The default algorithm is random weighted.
109
110 =head1 NOTES
111
112 The consistancy betweeen master and replicants is database specific.  The Pool
113 gives you a method to validate its replicants, removing and replacing them
114 when they fail/pass predefined criteria.  Please make careful use of the ways
115 to force a query to run against Master when needed.
116
117 =head1 REQUIREMENTS
118
119 Replicated Storage has additional requirements not currently part of L<DBIx::Class>
120
121   Moose => '0.90',
122   MooseX::Types => '0.16',
123   namespace::clean => '0.11',
124   Hash::Merge => '0.11'
125
126 You will need to install these modules manually via CPAN or make them part of the
127 Makefile for your distribution.
128
129 =head1 ATTRIBUTES
130
131 This class defines the following attributes.
132
133 =head2 schema
134
135 The underlying L<DBIx::Class::Schema> object this storage is attaching
136
137 =cut
138
139 has 'schema' => (
140     is=>'rw',
141     isa=>DBICSchema,
142     weak_ref=>1,
143     required=>1,
144 );
145
146 =head2 pool_type
147
148 Contains the classname which will instantiate the L</pool> object.  Defaults 
149 to: L<DBIx::Class::Storage::DBI::Replicated::Pool>.
150
151 =cut
152
153 has 'pool_type' => (
154   is=>'rw',
155   isa=>ClassName,
156   default=>'DBIx::Class::Storage::DBI::Replicated::Pool',
157   handles=>{
158     'create_pool' => 'new',
159   },
160 );
161
162 =head2 pool_args
163
164 Contains a hashref of initialized information to pass to the Balancer object.
165 See L<DBIx::Class::Storage::DBI::Replicated::Pool> for available arguments.
166
167 =cut
168
169 has 'pool_args' => (
170   is=>'rw',
171   isa=>HashRef,
172   lazy=>1,
173   default=>sub { {} },
174 );
175
176
177 =head2 balancer_type
178
179 The replication pool requires a balance class to provider the methods for
180 choose how to spread the query load across each replicant in the pool.
181
182 =cut
183
184 has 'balancer_type' => (
185   is=>'rw',
186   isa=>BalancerClassNamePart,
187   coerce=>1,
188   required=>1,
189   default=> 'DBIx::Class::Storage::DBI::Replicated::Balancer::First',
190   handles=>{
191     'create_balancer' => 'new',
192   },
193 );
194
195 =head2 balancer_args
196
197 Contains a hashref of initialized information to pass to the Balancer object.
198 See L<DBIx::Class::Storage::DBI::Replicated::Balancer> for available arguments.
199
200 =cut
201
202 has 'balancer_args' => (
203   is=>'rw',
204   isa=>HashRef,
205   lazy=>1,
206   required=>1,
207   default=>sub { {} },
208 );
209
210 =head2 pool
211
212 Is a <DBIx::Class::Storage::DBI::Replicated::Pool> or derived class.  This is a
213 container class for one or more replicated databases.
214
215 =cut
216
217 has 'pool' => (
218   is=>'ro',
219   isa=>'DBIx::Class::Storage::DBI::Replicated::Pool',
220   lazy_build=>1,
221   handles=>[qw/
222     connect_replicants
223     replicants
224     has_replicants
225   /],
226 );
227
228 =head2 balancer
229
230 Is a <DBIx::Class::Storage::DBI::Replicated::Balancer> or derived class.  This 
231 is a class that takes a pool (<DBIx::Class::Storage::DBI::Replicated::Pool>)
232
233 =cut
234
235 has 'balancer' => (
236   is=>'rw',
237   isa=>'DBIx::Class::Storage::DBI::Replicated::Balancer',
238   lazy_build=>1,
239   handles=>[qw/auto_validate_every/],
240 );
241
242 =head2 master
243
244 The master defines the canonical state for a pool of connected databases.  All
245 the replicants are expected to match this databases state.  Thus, in a classic
246 Master / Slaves distributed system, all the slaves are expected to replicate
247 the Master's state as quick as possible.  This is the only database in the
248 pool of databases that is allowed to handle write traffic.
249
250 =cut
251
252 has 'master' => (
253   is=> 'ro',
254   isa=>DBICStorageDBI,
255   lazy_build=>1,
256 );
257
258 =head1 ATTRIBUTES IMPLEMENTING THE DBIx::Storage::DBI INTERFACE
259
260 The following methods are delegated all the methods required for the 
261 L<DBIx::Class::Storage::DBI> interface.
262
263 =head2 read_handler
264
265 Defines an object that implements the read side of L<BIx::Class::Storage::DBI>.
266
267 =cut
268
269 has 'read_handler' => (
270   is=>'rw',
271   isa=>Object,
272   lazy_build=>1,
273   handles=>[qw/
274     select
275     select_single
276     columns_info_for
277   /],
278 );
279
280 =head2 write_handler
281
282 Defines an object that implements the write side of L<BIx::Class::Storage::DBI>.
283
284 =cut
285
286 has 'write_handler' => (
287   is=>'ro',
288   isa=>Object,
289   lazy_build=>1,
290   handles=>[qw/
291     on_connect_do
292     on_disconnect_do
293     connect_info
294     throw_exception
295     sql_maker
296     sqlt_type
297     create_ddl_dir
298     deployment_statements
299     datetime_parser
300     datetime_parser_type
301     build_datetime_parser
302     last_insert_id
303     insert
304     insert_bulk
305     update
306     delete
307     dbh
308     txn_begin
309     txn_do
310     txn_commit
311     txn_rollback
312     txn_scope_guard
313     sth
314     deploy
315     with_deferred_fk_checks
316     dbh_do
317     reload_row
318     with_deferred_fk_checks
319     _prep_for_execute
320
321     backup
322     is_datatype_numeric
323     _count_select
324     _subq_count_select
325     _subq_update_delete
326     svp_rollback
327     svp_begin
328     svp_release
329   /],
330 );
331
332 has _master_connect_info_opts =>
333   (is => 'rw', isa => HashRef, default => sub { {} });
334
335 =head2 around: connect_info
336
337 Preserve master's C<connect_info> options (for merging with replicants.)
338 Also set any Replicated related options from connect_info, such as
339 C<pool_type>, C<pool_args>, C<balancer_type> and C<balancer_args>.
340
341 =cut
342
343 around connect_info => sub {
344   my ($next, $self, $info, @extra) = @_;
345
346   my $wantarray = wantarray;
347
348   my %opts;
349   for my $arg (@$info) {
350     next unless (reftype($arg)||'') eq 'HASH';
351     %opts = %{ merge($arg, \%opts) };
352   }
353   delete $opts{dsn};
354
355   if (@opts{qw/pool_type pool_args/}) {
356     $self->pool_type(delete $opts{pool_type})
357       if $opts{pool_type};
358
359     $self->pool_args(
360       merge((delete $opts{pool_args} || {}), $self->pool_args)
361     );
362
363     $self->pool($self->_build_pool)
364       if $self->pool;
365   }
366
367   if (@opts{qw/balancer_type balancer_args/}) {
368     $self->balancer_type(delete $opts{balancer_type})
369       if $opts{balancer_type};
370
371     $self->balancer_args(
372       merge((delete $opts{balancer_args} || {}), $self->balancer_args)
373     );
374
375     $self->balancer($self->_build_balancer)
376       if $self->balancer;
377   }
378
379   $self->_master_connect_info_opts(\%opts);
380
381   my (@res, $res);
382   if ($wantarray) {
383     @res = $self->$next($info, @extra);
384   } else {
385     $res = $self->$next($info, @extra);
386   }
387
388   # Make sure master is blessed into the correct class and apply role to it.
389   my $master = $self->master;
390   $master->_determine_driver;
391   Moose::Meta::Class->initialize(ref $master);
392   DBIx::Class::Storage::DBI::Replicated::WithDSN->meta->apply($master);
393
394   $wantarray ? @res : $res;
395 };
396
397 =head1 METHODS
398
399 This class defines the following methods.
400
401 =head2 BUILDARGS
402
403 L<DBIx::Class::Schema> when instantiating its storage passed itself as the
404 first argument.  So we need to massage the arguments a bit so that all the
405 bits get put into the correct places.
406
407 =cut
408
409 sub BUILDARGS {
410   my ($class, $schema, $storage_type_args, @args) = @_; 
411
412   return {
413     schema=>$schema,
414     %$storage_type_args,
415     @args
416   }
417 }
418
419 =head2 _build_master
420
421 Lazy builder for the L</master> attribute.
422
423 =cut
424
425 sub _build_master {
426   my $self = shift @_;
427   my $master = DBIx::Class::Storage::DBI->new($self->schema);
428   $master
429 }
430
431 =head2 _build_pool
432
433 Lazy builder for the L</pool> attribute.
434
435 =cut
436
437 sub _build_pool {
438   my $self = shift @_;
439   $self->create_pool(%{$self->pool_args});
440 }
441
442 =head2 _build_balancer
443
444 Lazy builder for the L</balancer> attribute.  This takes a Pool object so that
445 the balancer knows which pool it's balancing.
446
447 =cut
448
449 sub _build_balancer {
450   my $self = shift @_;
451   $self->create_balancer(
452     pool=>$self->pool,
453     master=>$self->master,
454     %{$self->balancer_args},
455   );
456 }
457
458 =head2 _build_write_handler
459
460 Lazy builder for the L</write_handler> attribute.  The default is to set this to
461 the L</master>.
462
463 =cut
464
465 sub _build_write_handler {
466   return shift->master;
467 }
468
469 =head2 _build_read_handler
470
471 Lazy builder for the L</read_handler> attribute.  The default is to set this to
472 the L</balancer>.
473
474 =cut
475
476 sub _build_read_handler {
477   return shift->balancer;
478 }
479
480 =head2 around: connect_replicants
481
482 All calls to connect_replicants needs to have an existing $schema tacked onto
483 top of the args, since L<DBIx::Storage::DBI> needs it, and any C<connect_info>
484 options merged with the master, with replicant opts having higher priority.
485
486 =cut
487
488 around connect_replicants => sub {
489   my ($next, $self, @args) = @_;
490
491   for my $r (@args) {
492     $r = [ $r ] unless reftype $r eq 'ARRAY';
493
494     $self->throw_exception('coderef replicant connect_info not supported')
495       if ref $r->[0] && reftype $r->[0] eq 'CODE';
496
497 # any connect_info options?
498     my $i = 0;
499     $i++ while $i < @$r && (reftype($r->[$i])||'') ne 'HASH';
500
501 # make one if none
502     $r->[$i] = {} unless $r->[$i];
503
504 # merge if two hashes
505     my @hashes = @$r[$i .. $#{$r}];
506
507     $self->throw_exception('invalid connect_info options')
508       if (grep { reftype($_) eq 'HASH' } @hashes) != @hashes;
509
510     $self->throw_exception('too many hashrefs in connect_info')
511       if @hashes > 2;
512
513     my %opts = %{ merge(reverse @hashes) };
514
515 # delete them
516     splice @$r, $i+1, ($#{$r} - $i), ();
517
518 # make sure master/replicants opts don't clash
519     my %master_opts = %{ $self->_master_connect_info_opts };
520     if (exists $opts{dbh_maker}) {
521         delete @master_opts{qw/dsn user password/};
522     }
523     delete $master_opts{dbh_maker};
524
525 # merge with master
526     %opts = %{ merge(\%opts, \%master_opts) };
527
528 # update
529     $r->[$i] = \%opts;
530   }
531
532   $self->$next($self->schema, @args);
533 };
534
535 =head2 all_storages
536
537 Returns an array of of all the connected storage backends.  The first element
538 in the returned array is the master, and the remainings are each of the
539 replicants.
540
541 =cut
542
543 sub all_storages {
544   my $self = shift @_;
545   return grep {defined $_ && blessed $_} (
546      $self->master,
547      values %{ $self->replicants },
548   );
549 }
550
551 =head2 execute_reliably ($coderef, ?@args)
552
553 Given a coderef, saves the current state of the L</read_handler>, forces it to
554 use reliable storage (ie sets it to the master), executes a coderef and then
555 restores the original state.
556
557 Example:
558
559   my $reliably = sub {
560     my $name = shift @_;
561     $schema->resultset('User')->create({name=>$name});
562     my $user_rs = $schema->resultset('User')->find({name=>$name}); 
563     return $user_rs;
564   };
565
566   my $user_rs = $schema->storage->execute_reliably($reliably, 'John');
567
568 Use this when you must be certain of your database state, such as when you just
569 inserted something and need to get a resultset including it, etc.
570
571 =cut
572
573 sub execute_reliably {
574   my ($self, $coderef, @args) = @_;
575
576   unless( ref $coderef eq 'CODE') {
577     $self->throw_exception('Second argument must be a coderef');
578   }
579
580   ##Get copy of master storage
581   my $master = $self->master;
582
583   ##Get whatever the current read hander is
584   my $current = $self->read_handler;
585
586   ##Set the read handler to master
587   $self->read_handler($master);
588
589   ## do whatever the caller needs
590   my @result;
591   my $want_array = wantarray;
592
593   eval {
594     if($want_array) {
595       @result = $coderef->(@args);
596     } elsif(defined $want_array) {
597       ($result[0]) = ($coderef->(@args));
598     } else {
599       $coderef->(@args);
600     }
601   };
602
603   ##Reset to the original state
604   $self->read_handler($current);
605
606   ##Exception testing has to come last, otherwise you might leave the 
607   ##read_handler set to master.
608
609   if($@) {
610     $self->throw_exception("coderef returned an error: $@");
611   } else {
612     return $want_array ? @result : $result[0];
613   }
614 }
615
616 =head2 set_reliable_storage
617
618 Sets the current $schema to be 'reliable', that is all queries, both read and
619 write are sent to the master
620
621 =cut
622
623 sub set_reliable_storage {
624   my $self = shift @_;
625   my $schema = $self->schema;
626   my $write_handler = $self->schema->storage->write_handler;
627
628   $schema->storage->read_handler($write_handler);
629 }
630
631 =head2 set_balanced_storage
632
633 Sets the current $schema to be use the </balancer> for all reads, while all
634 writea are sent to the master only
635
636 =cut
637
638 sub set_balanced_storage {
639   my $self = shift @_;
640   my $schema = $self->schema;
641   my $balanced_handler = $self->schema->storage->balancer;
642
643   $schema->storage->read_handler($balanced_handler);
644 }
645
646 =head2 connected
647
648 Check that the master and at least one of the replicants is connected.
649
650 =cut
651
652 sub connected {
653   my $self = shift @_;
654   return
655     $self->master->connected &&
656     $self->pool->connected_replicants;
657 }
658
659 =head2 ensure_connected
660
661 Make sure all the storages are connected.
662
663 =cut
664
665 sub ensure_connected {
666   my $self = shift @_;
667   foreach my $source ($self->all_storages) {
668     $source->ensure_connected(@_);
669   }
670 }
671
672 =head2 limit_dialect
673
674 Set the limit_dialect for all existing storages
675
676 =cut
677
678 sub limit_dialect {
679   my $self = shift @_;
680   foreach my $source ($self->all_storages) {
681     $source->limit_dialect(@_);
682   }
683   return $self->master->quote_char;
684 }
685
686 =head2 quote_char
687
688 Set the quote_char for all existing storages
689
690 =cut
691
692 sub quote_char {
693   my $self = shift @_;
694   foreach my $source ($self->all_storages) {
695     $source->quote_char(@_);
696   }
697   return $self->master->quote_char;
698 }
699
700 =head2 name_sep
701
702 Set the name_sep for all existing storages
703
704 =cut
705
706 sub name_sep {
707   my $self = shift @_;
708   foreach my $source ($self->all_storages) {
709     $source->name_sep(@_);
710   }
711   return $self->master->name_sep;
712 }
713
714 =head2 set_schema
715
716 Set the schema object for all existing storages
717
718 =cut
719
720 sub set_schema {
721   my $self = shift @_;
722   foreach my $source ($self->all_storages) {
723     $source->set_schema(@_);
724   }
725 }
726
727 =head2 debug
728
729 set a debug flag across all storages
730
731 =cut
732
733 sub debug {
734   my $self = shift @_;
735   if(@_) {
736     foreach my $source ($self->all_storages) {
737       $source->debug(@_);
738     }
739   }
740   return $self->master->debug;
741 }
742
743 =head2 debugobj
744
745 set a debug object across all storages
746
747 =cut
748
749 sub debugobj {
750   my $self = shift @_;
751   if(@_) {
752     foreach my $source ($self->all_storages) {
753       $source->debugobj(@_);
754     }
755   }
756   return $self->master->debugobj;
757 }
758
759 =head2 debugfh
760
761 set a debugfh object across all storages
762
763 =cut
764
765 sub debugfh {
766   my $self = shift @_;
767   if(@_) {
768     foreach my $source ($self->all_storages) {
769       $source->debugfh(@_);
770     }
771   }
772   return $self->master->debugfh;
773 }
774
775 =head2 debugcb
776
777 set a debug callback across all storages
778
779 =cut
780
781 sub debugcb {
782   my $self = shift @_;
783   if(@_) {
784     foreach my $source ($self->all_storages) {
785       $source->debugcb(@_);
786     }
787   }
788   return $self->master->debugcb;
789 }
790
791 =head2 disconnect
792
793 disconnect everything
794
795 =cut
796
797 sub disconnect {
798   my $self = shift @_;
799   foreach my $source ($self->all_storages) {
800     $source->disconnect(@_);
801   }
802 }
803
804 =head2 cursor_class
805
806 set cursor class on all storages, or return master's
807
808 =cut
809
810 sub cursor_class {
811   my ($self, $cursor_class) = @_;
812
813   if ($cursor_class) {
814     $_->cursor_class($cursor_class) for $self->all_storages;
815   }
816   $self->master->cursor_class;
817 }
818
819 =head1 GOTCHAS
820
821 Due to the fact that replicants can lag behind a master, you must take care to
822 make sure you use one of the methods to force read queries to a master should
823 you need realtime data integrity.  For example, if you insert a row, and then
824 immediately re-read it from the database (say, by doing $row->discard_changes)
825 or you insert a row and then immediately build a query that expects that row
826 to be an item, you should force the master to handle reads.  Otherwise, due to
827 the lag, there is no certainty your data will be in the expected state.
828
829 For data integrity, all transactions automatically use the master storage for
830 all read and write queries.  Using a transaction is the preferred and recommended
831 method to force the master to handle all read queries.
832
833 Otherwise, you can force a single query to use the master with the 'force_pool'
834 attribute:
835
836   my $row = $resultset->search(undef, {force_pool=>'master'})->find($pk);
837
838 This attribute will safely be ignore by non replicated storages, so you can use
839 the same code for both types of systems.
840
841 Lastly, you can use the L</execute_reliably> method, which works very much like
842 a transaction.
843
844 For debugging, you can turn replication on/off with the methods L</set_reliable_storage>
845 and L</set_balanced_storage>, however this operates at a global level and is not
846 suitable if you have a shared Schema object being used by multiple processes,
847 such as on a web application server.  You can get around this limitation by
848 using the Schema clone method.
849
850   my $new_schema = $schema->clone;
851   $new_schema->set_reliable_storage;
852
853   ## $new_schema will use only the Master storage for all reads/writes while
854   ## the $schema object will use replicated storage.
855
856 =head1 AUTHOR
857
858   John Napiorkowski <john.napiorkowski@takkle.com>
859
860 Based on code originated by:
861
862   Norbert Csongrádi <bert@cpan.org>
863   Peter Siklósi <einon@einon.hu>
864
865 =head1 LICENSE
866
867 You may distribute this code under the same terms as Perl itself.
868
869 =cut
870
871 __PACKAGE__->meta->make_immutable;
872
873 1;