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