convert from the bottom up
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Storage / DBI / Replicated / Balancer / Random.pm
1 package DBIx::Class::Storage::DBI::Replicated::Balancer::Random;
2
3 use Moo;
4 use DBIx::Class::Storage::DBI::Replicated::Types qw(PositiveNumber);
5 with 'DBIx::Class::Storage::DBI::Replicated::Balancer';
6
7 =head1 NAME
8
9 DBIx::Class::Storage::DBI::Replicated::Balancer::Random - A 'random' Balancer
10
11 =head1 SYNOPSIS
12
13 This class is used internally by L<DBIx::Class::Storage::DBI::Replicated>.  You
14 shouldn't need to create instances of this class.
15
16 =head1 DESCRIPTION
17
18 Given a pool (L<DBIx::Class::Storage::DBI::Replicated::Pool>) of replicated
19 database's (L<DBIx::Class::Storage::DBI::Replicated::Replicant>), defines a
20 method by which query load can be spread out across each replicant in the pool.
21
22 =head1 ATTRIBUTES
23
24 This class defines the following attributes.
25
26 =head2 master_read_weight
27
28 A number greater than 0 that specifies what weight to give the master when
29 choosing which backend to execute a read query on. A value of 0, which is the
30 default, does no reads from master, while a value of 1 gives it the same
31 priority as any single replicant.
32
33 For example: if you have 2 replicants, and a L</master_read_weight> of C<0.5>,
34 the chance of reading from master will be C<20%>.
35
36 You can set it to a value higher than 1, making master have higher weight than
37 any single replicant, if for example you have a very powerful master.
38
39 =cut
40
41 has master_read_weight => (
42   is => 'rw',
43   isa => PositiveNumber(err => sub {"weight must be a positive number, not $_[0]"}),
44   default => sub { 0 },
45 );
46
47 =head1 METHODS
48
49 This class defines the following methods.
50
51 =head2 next_storage
52
53 Returns an active replicant at random.  Please note that due to the nature of
54 the word 'random' this means it's possible for a particular active replicant to
55 be requested several times in a row.
56
57 =cut
58
59 sub next_storage {
60   my $self = shift;
61   my @replicants = $self->pool->active_replicants;
62
63   if (not @replicants) {
64     # will fall back to master anyway
65     return;
66   }
67
68   my $master = $self->master;
69   my $rnd = $self->_random_number(@replicants + $self->master_read_weight);
70
71   return $rnd >= @replicants ? $master : $replicants[int $rnd];
72 }
73
74 sub _random_number {
75   rand($_[1]);
76 }
77
78 =head1 AUTHOR
79
80 John Napiorkowski <jjnapiork@cpan.org>
81
82 =head1 LICENSE
83
84 You may distribute this code under the same terms as Perl itself.
85
86 =cut
87
88 1;