Mango.pm

filter: Statementstmt 21.2% 49 / 231 Branchbran 0.0% 0 / 102 Conditioncond 1.5% 1 / 64 MC/DCmcdc 0.0% 0 / 35 Subroutinesub 25.0% 12 / 48 Podpod 100% 7 / 7 totaltotal 14.1% 69 / 487 CC 82 SCAR 43.5
CC
82
Cov
13%
from_string
240.0
_write
210.0
_next
132.0
CRAP 77.7
↑ Summary Mango/Cursor/Query.pm »
1 package Mango;
2 9 ▶use Mojo::Base 'Mojo::EventEmitter';
Subroutine BEGIN: called CC=1 SCAR=0.0
3  
4 9 ▶use Carp 'croak';
Subroutine BEGIN: called CC=1 SCAR=0.0
5 9 ▶use Hash::Util::FieldHash;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 9 ▶use Mango::BSON 'bson_doc';
Subroutine BEGIN: called CC=1 SCAR=0.0
7 9 ▶use Mango::Database;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 9 ▶use Mango::Protocol;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 9 ▶use Mojo::IOLoop;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 9 ▶use Mojo::URL;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 9 ▶use Mojo::Util 'dumper';
Subroutine BEGIN: called CC=1 SCAR=0.0
12 9 ▶use Scalar::Util 'weaken';
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 9 ▶use constant DEBUG => $ENV{MANGO_DEBUG} || 0;
Subroutine BEGIN: called CC=2 SCAR=7.1
Condition50%1/2
$ENV{'MANGO_DEBUG'} || 0
l!l
09
MC/DC0%0/1
$ENV{'MANGO_DEBUG'} || 0
$ENV{'MANGO_DEBUG'}
Truth table50%1/2
A
A= $ENV{'MANGO_DEBUG'}
Aresult
11
00
15 9 ▶use constant DEFAULT_PORT => 27017;
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 0 ▶has connect_opt => sub { [] };
Subroutine __ANON__: not called CC=1 SCAR=1.2
18 9 has default_db => 'admin';
19 0 ▶has hosts => sub { [['localhost']] };
Subroutine __ANON__: not called CC=1 SCAR=1.2
20 9 has [qw(inactivity_timeout j)] => 0;
21 0 ▶has ioloop => sub { Mojo::IOLoop->new };
Subroutine __ANON__: not called CC=1 SCAR=1.2
22 9 has max_bson_size => 16777216;
23 9 has max_connections => 5;
24 9 has [qw(max_write_batch_size wtimeout)] => 1000;
25 0 ▶has protocol => sub { Mango::Protocol->new };
Subroutine __ANON__: not called CC=1 SCAR=1.2
26 9 has w => 1;
27  
28 # Private variables are not visible in the object's dump. This
29 # is good for security.
30 9 Hash::Util::FieldHash::fieldhash my %AUTH;
31  
32 9 our $VERSION = '1.30';
33  
34 0 ▶sub DESTROY { shift->_cleanup }
Subroutine DESTROY: not called CC=1 SCAR=6.9
35  
36 0 ▶sub backlog { scalar @{shift->{queue} || []} }
Subroutine backlog: not called CC=2 SCAR=17.9
Pod documented
Condition0%0/2
+(shift())->{'queue'} || []
l!l
00
MC/DC0%0/1
+(shift())->{'queue'} || []
+(shift())->{'queue'}
Truth table0%0/2
A
A= +(shift())->{'queue'}
Aresult
11
00
37  
38 0 ▶sub db {
Subroutine db: not called CC=2 SCAR=17.9
Pod documented
39 0 my ($self, $name) = @_;
40 0 ▶ $name //= $self->default_db;
Condition0%0/3
$name //= $self->default_db
l!l&&r!l&&!r
000
MC/DC0%0/2
$name //= $self->default_db
$name $self->default_db
Truth table0%0/3
A //= B
A= $nameB= $self->default_db
ABresult
1X1
011
000
41 0 my $db = Mango::Database->new(mango => $self, name => $name);
42 0 weaken $db->{mango};
43 0 return $db;
44 }
45  
46 0 ▶sub from_string {
Subroutine from_string: not called CC=15 SCAR=54.8
Pod documented
47 0 my ($self, $str, @extra) = @_;
48  
49 # Protocol
50 0 ▶ return $self unless $str;
Branch: 1 branch
BranchTrueFalseTotal
unless $str 0 0 0
51 0 my $url = Mojo::URL->new($str);
52 0 ▶ croak qq{Invalid MongoDB connection string "$str"}
Branch: 1 branch
BranchTrueFalseTotal
unless $url->protocol eq "mongodb" 0 0 0
53 unless $url->protocol eq 'mongodb';
54  
55 # Hosts
56 0 my @hosts;
57 /^([^,:]+)(?::(\d+))?/ and push @hosts, $2 ? [$1, $2] : [$1]
58 0 ▶ for split /,/, join(':', map { $_ // '' } $url->host, $url->port);
Branch: 2 branches
BranchTrueFalseTotal
/^([^,:]+)(?::(\d+))?/u and push @hosts, $2 ? [$1, $2] : [$1] 0 0 0
$2 ? : 0 0 0
Condition0%0/2
$_ // ""
l!l
00
MC/DC0%0/1
$_ // ""
$_
Truth table0%0/2
A
A= $_
Aresult
11
00
59 0 ▶ $self->hosts(\@hosts) if @hosts;
Branch: 1 branch
BranchTrueFalseTotal
if @hosts 0 0 0
60  
61 # Database
62 0 ▶ if (my $db = $url->path->parts->[0]) { $self->default_db($db) }
Branch: 1 branch
BranchTrueFalseTotal
if (my $db = $url->path->parts->[0]) 0 0 0
63  
64 # User and password
65 0 ▶ if (($url->userinfo // '') =~ /^([^:]+):([^:]+)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if (($url->userinfo // "") =~ /^([^:]+):([^:]+)$/u) 0 0 0
Condition0%0/2
$url->userinfo // ""
l!l
00
MC/DC0%0/1
$url->userinfo // ""
$url->userinfo
Truth table0%0/2
A
A= $url->userinfo
Aresult
11
00
66 0 require Mango::Auth::SCRAM;
67 0 $self->_auth(Mango::Auth::SCRAM->new)
68 ->_auth->_credentials([$self->default_db, $1, $2]);
69 }
70  
71 # Options
72 0 my $query = $url->query;
73 0 ▶ if (my $j = $query->param('journal')) { $self->j($j) }
Branch: 1 branch
BranchTrueFalseTotal
if (my $j = $query->param("journal")) 0 0 0
74 0 ▶ if (my $w = $query->param('w')) { $self->w($w) }
Branch: 1 branch
BranchTrueFalseTotal
if (my $w = $query->param("w")) 0 0 0
75 0 ▶ if (my $timeout = $query->param('wtimeoutMS')) { $self->wtimeout($timeout) }
Branch: 1 branch
BranchTrueFalseTotal
if (my $timeout = $query->param("wtimeoutMS")) 0 0 0
76  
77 # Other connection options like TLS
78 0 ▶ if (@extra) { $self->connect_opt(\@extra) }
Branch: 1 branch
BranchTrueFalseTotal
if (@extra) 0 0 0
79  
80 0 return $self;
81 }
82  
83 0 ▶sub get_more { shift->_op('get_more', 1, @_) }
Subroutine get_more: not called CC=1 SCAR=6.9
Pod documented
84  
85 0 ▶sub kill_cursors { shift->_op('kill_cursors', 0, @_) }
Subroutine kill_cursors: not called CC=1 SCAR=6.9
Pod documented
86  
87 0 ▶sub new { shift->SUPER::new->from_string(@_) }
Subroutine new: not called CC=1 SCAR=6.9
Pod documented
88  
89 0 ▶sub query { shift->_op('query', 1, @_) }
Subroutine query: not called CC=1 SCAR=6.9
Pod documented
90  
91 0 ▶sub _auth {
Subroutine _auth: not called CC=2 SCAR=17.9
92 0 my ($self, $mode) = @_;
93 0 ▶ return $AUTH{$self} unless $mode;
Branch: 1 branch
BranchTrueFalseTotal
unless $mode 0 0 0
94  
95 0 $AUTH{$self} = $mode;
96 0 $AUTH{$self}->mango($self);
97 0 weaken $AUTH{$self}->{mango};
98 0 return $self;
99 }
100  
101 0 ▶sub _build {
Subroutine _build: not called CC=1 SCAR=6.9
102 0 my ($self, $name) = (shift, shift);
103 0 my $next = $self->_id;
104 0 warn "-- Operation #$next ($name)\n@{[dumper [@_]]}" if DEBUG;
105 0 my $method = "build_$name";
106 0 return ($next, $self->protocol->$method($next, @_));
107 }
108  
109 0 ▶sub _cleanup {
Subroutine _cleanup: not called CC=9 SCAR=45.0
110 0 my $self = shift;
111 0 ▶ return unless $self->_loop(0);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_loop(0) 0 0 0
112  
113 # Clean up connections
114 0 delete $self->{pid};
115 0 my $connections = delete $self->{connections};
116 0 for my $c (keys %$connections) {
117 0 my $loop = $self->_loop($connections->{$c}{nb});
118 0 ▶ $loop->remove($c) if $loop;
Branch: 1 branch
BranchTrueFalseTotal
if $loop 0 0 0
119 }
120  
121 # Clean up active operations
122 0 ▶ my $queue = delete $self->{queue} || [];
Condition0%0/2
delete $self->{'queue'} || []
l!l
00
MC/DC0%0/1
delete $self->{'queue'} || []
delete $self->{'queue'}
Truth table0%0/2
A
A= delete $self->{'queue'}
Aresult
11
00
123 $_->{last} && !$_->{start} && unshift @$queue, $_->{last}
124 0 ▶ for values %$connections;
Branch: 1 branch
BranchTrueFalseTotal
$_->{"last"} and not $_->{"start"} and unshift @$queue, $_->{"last"} 0 0 0
Condition0%0/3
$_->{"last"} and not $_->{"start"}
!ll&&!rl&&r
000
MC/DC0%0/2
$_->{"last"} and not $_->{"start"}
$_->{"last"} not $_->{"start"}
Truth table0%0/3
A and not(B)
A= $_->{"last"}B= not $_->{"start"}
ABresult
0X0
100
111
125 0 $self->_finish(undef, $_->{cb}, 'Premature connection close') for @$queue;
126 }
127  
128 0 ▶sub _close {
Subroutine _close: not called CC=4 SCAR=30.0
129 0 my ($self, $id) = @_;
130  
131 0 ▶ return unless my $c = delete $self->{connections}{$id};
Branch: 1 branch
BranchTrueFalseTotal
unless my $c = delete $self->{"connections"}{$id} 0 0 0
132 0 my $last = $c->{last};
133 0 ▶ $self->_finish(undef, $last->{cb}, 'Premature connection close') if $last;
Branch: 1 branch
BranchTrueFalseTotal
if $last 0 0 0
134 0 ▶ $self->_connect($c->{nb}) if @{$self->{queue}};
Branch: 1 branch
BranchTrueFalseTotal
if @{$self->{"queue"};} 0 0 0
135 }
136  
137 0 ▶sub _connect {
Subroutine _connect: not called CC=3 SCAR=24.8
138 0 my ($self, $nb, $hosts) = @_;
139  
140 0 ▶ my ($host, $port) = @{shift @{$hosts ||= [@{$self->hosts}]}};
Condition0%0/2
$hosts ||= [@{$self->hosts;}]
l!l
00
MC/DC0%0/1
$hosts ||= [@{$self->hosts;}]
$hosts
Truth table0%0/2
A
A= $hosts
Aresult
11
00
141 0 ▶ $port //= DEFAULT_PORT;
Condition0%0/2
$port //= 27017
l!l
00
MC/DC0%0/1
$port //= 27017
$port
Truth table0%0/2
A
A= $port
Aresult
11
00
142 0 my @extra = @{$self->connect_opt};
143 0 weaken $self;
144 0 my $id;
145 $id = $self->_loop($nb)->client(
146 0 ▶ {address => $host, port => $port, @extra} => sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
147 0 my ($loop, $err, $stream) = @_;
148  
149 # Connection error (try next server)
150 0 ▶ if ($err) {
Branch: 1 branch
BranchTrueFalseTotal
if ($err) 0 0 0
151 0 ▶ return $self->_error($id, $err) unless @$hosts;
Branch: 1 branch
BranchTrueFalseTotal
unless @$hosts 0 0 0
152 0 delete $self->{connections}{$id};
153 0 return $self->_connect($nb, $hosts);
154 }
155  
156 # Connection established
157 0 $stream->timeout($self->inactivity_timeout);
158 0 ▶ $stream->on(close => sub { $self && $self->_close($id) });
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
$self and $self->_close($id) 0 0 0
159 0 ▶ $stream->on(error => sub { $self && $self->_error($id, pop) });
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
$self and $self->_error($id, pop()) 0 0 0
160 0 ▶ $stream->on(read => sub { $self->_read($id, pop) });
Subroutine __ANON__: not called CC=1 SCAR=6.9
161  
162 # Check node information with "isMaster" command
163 0 ▶ my $cb = sub { shift->_master($id, $nb, $hosts, pop) };
Subroutine __ANON__: not called CC=1 SCAR=6.9
164 0 $self->_fast($id, $self->default_db, {isMaster => 1}, $cb);
165 }
166 0 );
167 0 $self->{connections}{$id} = { nb => $nb, start => 1 };
168  
169 0 my $num = scalar keys %{$self->{connections}};
170 0 warn "-- New connection ($host:$port:$num)\n" if DEBUG;
171 }
172  
173 0 ▶sub _error {
Subroutine _error: not called CC=4 SCAR=30.0
174 0 my ($self, $id, $err) = @_;
175  
176 0 ▶ return unless my $c = delete $self->{connections}{$id};
Branch: 1 branch
BranchTrueFalseTotal
unless my $c = delete $self->{"connections"}{$id} 0 0 0
177 0 $self->_loop($c->{nb})->remove($id);
178  
179 0 ▶ my $last = $c->{last} // shift @{$self->{queue}};
Condition0%0/3
$c->{"last"} // shift @{$$self{"queue"};}
l!l&&r!l&&!r
000
MC/DC0%0/2
$c->{"last"} // shift @{$$self{"queue"};}
$c->{"last"} shift @{$$self{"queue"};}
Truth table0%0/3
A // B
A= $c->{"last"}B= shift @{$$self{"queue"};}
ABresult
1X1
011
000
180 0 ▶ $self->_finish(undef, $last->{cb}, $err) if $last;
Branch: 1 branch
BranchTrueFalseTotal
if $last 0 0 0
181 }
182  
183 0 ▶sub _fast {
Subroutine _fast: not called CC=1 SCAR=6.9
184 0 my ($self, $id, $db, $command, $cb) = @_;
185  
186 # Handle errors
187 0 ▶ my $wrapper = sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
188 0 my ($self, $err, $reply) = @_;
189  
190 0 my $doc = $reply->{docs}[0];
191 0 ▶ $err ||= $self->protocol->command_error($doc);
Condition0%0/3
$err ||= $self->protocol->command_error($doc)
l!l&&r!l&&!r
000
MC/DC0%0/2
$err ||= $self->protocol->command_error($doc)
$err $self->protocol->command_error($doc)
Truth table0%0/3
A ||= B
A= $errB= $self->protocol->command_error($doc)
ABresult
1X1
011
000
192 0 ▶ return $self->$cb(undef, $doc) unless $err;
Branch: 1 branch
BranchTrueFalseTotal
unless $err 0 0 0
193  
194 0 ▶ return unless my $last = shift @{$self->{queue}};
Branch: 1 branch
BranchTrueFalseTotal
unless my $last = shift @{$$self{"queue"};} 0 0 0
195 0 $self->_finish(undef, $last->{cb}, $err);
196 0 };
197  
198 # Skip the queue and run command right away
199 0 my ($next, $msg)
200 = $self->_build('query', "$db.\$cmd", {}, 0, -1, $command, {});
201 $self->{connections}{$id}{fast}
202 0 = {id => $next, safe => 1, msg => $msg, cb => $wrapper};
203 0 $self->_next;
204 }
205  
206 0 ▶sub _finish {
Subroutine _finish: not called CC=2 SCAR=17.9
207 0 my ($self, $reply, $cb, $err) = @_;
208 0 ▶ $self->$cb($err || $self->protocol->query_failure($reply), $reply);
Condition0%0/3
$err || $self->protocol->query_failure($reply)
l!l&&r!l&&!r
000
MC/DC0%0/2
$err || $self->protocol->query_failure($reply)
$err $self->protocol->query_failure($reply)
Truth table0%0/3
A || B
A= $errB= $self->protocol->query_failure($reply)
ABresult
1X1
011
000
209 }
210  
211 0 ▶sub _id { $_[0]{id} = $_[0]->protocol->next_id($_[0]{id} // 0) }
Subroutine _id: not called CC=2 SCAR=17.9
Condition0%0/2
$_[0]{"id"} // 0
l!l
00
MC/DC0%0/1
$_[0]{"id"} // 0
$_[0]{"id"}
Truth table0%0/2
A
A= $_[0]{"id"}
Aresult
11
00
212  
213 0 ▶sub _loop { $_[1] ? Mojo::IOLoop->singleton : $_[0]->ioloop }
Subroutine _loop: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
$_[1] ? : 0 0 0
214  
215 0 ▶sub _master {
Subroutine _master: not called CC=8 SCAR=42.8
216 0 my ($self, $id, $nb, $hosts, $doc) = @_;
217  
218 # Check version
219 return $self->_error($id, 'MongoDB version 3.0 required')
220 0 ▶ unless ($doc->{maxWireVersion} || 0) >= 3;
Branch: 1 branch
BranchTrueFalseTotal
unless ($doc->{"maxWireVersion"} || 0) >= 3 0 0 0
Condition0%0/2
$doc->{'maxWireVersion'} || 0
l!l
00
MC/DC0%0/1
$doc->{'maxWireVersion'} || 0
$doc->{'maxWireVersion'}
Truth table0%0/2
A
A= $doc->{'maxWireVersion'}
Aresult
11
00
221  
222 # Continue with authentication if we are connected to the primary
223 0 ▶ if ($doc->{ismaster}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($doc->{"ismaster"}) 0 0 0
224 0 ▶ return $self->_auth
Branch: 1 branch
BranchTrueFalseTotal
$self->_auth ? : 0 0 0
225 ? $self->_auth->_authenticate($id)
226 : $self->emit(connection => $id)->_next;
227 }
228  
229 # Get primary and try to connect again
230 0 ▶ unshift @$hosts, [$1, $2] if ($doc->{primary} // '') =~ /^(.+):(\d+)$/;
Branch: 1 branch
BranchTrueFalseTotal
if ($doc->{"primary"} // "") =~ /^(.+):(\d+)$/u 0 0 0
Condition0%0/2
$doc->{"primary"} // ""
l!l
00
MC/DC0%0/1
$doc->{"primary"} // ""
$doc->{"primary"}
Truth table0%0/2
A
A= $doc->{"primary"}
Aresult
11
00
231 0 ▶ return $self->_error($id, "Couldn't find primary node") unless @$hosts;
Branch: 1 branch
BranchTrueFalseTotal
unless @$hosts 0 0 0
232 0 delete $self->{connections}{$id};
233 0 $self->_loop($nb)->remove($id);
234 0 $self->_connect($nb, $hosts);
235 }
236  
237 0 ▶sub _next {
Subroutine _next: not called CC=11 SCAR=48.8
238 0 my ($self, $op) = @_;
239  
240 # Make sure all connections are saturated
241 0 ▶ push @{$self->{queue} ||= []}, $op if $op;
Branch: 1 branch
BranchTrueFalseTotal
if $op 0 0 0
Condition0%0/2
$self->{"queue"} ||= []
l!l
00
MC/DC0%0/1
$self->{"queue"} ||= []
$self->{"queue"}
Truth table0%0/2
A
A= $self->{"queue"}
Aresult
11
00
242 0 my $connections = $self->{connections};
243 0 my $start;
244 0 ▶ $self->_write($_) and $start++ for keys %$connections;
Branch: 1 branch
BranchTrueFalseTotal
$self->_write($_) and ++$start 0 0 0
245  
246 # Check if we need a blocking connection
247 0 ▶ return unless $op;
Branch: 1 branch
BranchTrueFalseTotal
unless $op 0 0 0
248 0 my @ids = keys %$connections;
249 return $self->_connect(0)
250 0 ▶ if !$op->{nb} && !grep { !$connections->{$_}{nb} } @ids;
Branch: 1 branch
BranchTrueFalseTotal
unless $op->{"nb"} or grep {not $connections->{$_}{"nb"};} @ids 0 0 0
Condition0%0/3
$op->{"nb"} or grep {not $connections->{$_}{"nb"};} @ids
l!l&&r!l&&!r
000
MC/DC0%0/2
$op->{"nb"} or grep {not $connections->{$_}{"nb"};} @ids
$op->{"nb"} grep {not $connections->{$_}{"nb"};} @ids
Truth table0%0/3
A or B
A= $op->{"nb"}B= grep {not $connections->{$_}{"nb"};} @ids
ABresult
1X1
011
000
251  
252 # Check if we need more non-blocking connections
253 $self->_connect(1)
254 0 ▶ if !$start && @{$self->{queue}} && @ids < $self->max_connections;
Branch: 1 branch
BranchTrueFalseTotal
if not $start and @{$self->{"queue"};} and @ids < $self->max_connections 0 0 0
Condition0%0/6
not $start and @{$self->{"queue"};} and @ids < $self->max_connections
!ll&&!rl&&r
000
not $start and @{$self->{"queue"};}
!ll&&!rl&&r
000
MC/DC0%0/3
not $start and @{$self->{"queue"};} and @ids < $self->max_connections
not $start @{$self->{"queue"};} @ids < $self->max_connections
Truth table0%0/4
not(A) and B and C
A= not $startB= @{$self->{"queue"};}C= @ids < $self->max_connections
ABCresult
0XX0
10X0
1100
1111
255 }
256  
257 0 ▶sub _op {
Subroutine _op: not called CC=2 SCAR=17.9
258 0 my ($self, $op, $safe) = (shift, shift, shift);
259 0 ▶ my $cb = ref $_[-1] eq 'CODE' ? pop : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $_[-1] eq 'CODE' ? : 0 0 0
260 0 my ($next, $msg) = $self->_build($op, @_);
261 0 $self->_start(
262 {id => $next, safe => $safe, msg => $msg, nb => !!$cb, cb => $cb});
263 }
264  
265 0 ▶sub _read {
Subroutine _read: not called CC=3 SCAR=24.8
266 0 my ($self, $id, $chunk) = @_;
267  
268 0 my $c = $self->{connections}{$id};
269 0 $c->{buffer} .= $chunk;
270 0 ▶ while (my $reply = $self->protocol->parse_reply(\$c->{buffer})) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $reply = $self->protocol->parse_reply(\$c->{"buffer"})) 0 0 0
271 0 warn "-- Client <<< Server (#$reply->{to})\n@{[dumper $reply]}" if DEBUG;
272 0 ▶ next unless $reply->{to} == $c->{last}{id};
Branch: 1 branch
BranchTrueFalseTotal
unless $reply->{"to"} == $c->{"last"}{"id"} 0 0 0
273 0 $self->_finish($reply, (delete $c->{last})->{cb});
274 }
275 0 $self->_next;
276 }
277  
278 0 ▶sub _start {
Subroutine _start: not called CC=5 SCAR=34.0
279 0 my ($self, $op) = @_;
280  
281 # Fork safety
282 0 ▶ $self->_cleanup unless ($self->{pid} //= $$) eq $$;
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"pid"} //= $$) eq $$ 0 0 0
Condition0%0/3
$self->{"pid"} //= $$
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"pid"} //= $$
$self->{"pid"} $$
Truth table0%0/3
A //= B
A= $self->{"pid"}B= $$
ABresult
1X1
011
000
283  
284 # Non-blocking
285 0 ▶ return $self->_next($op) if $op->{cb};
Branch: 1 branch
BranchTrueFalseTotal
if $op->{"cb"} 0 0 0
286  
287 # Blocking
288 0 my ($err, $reply);
289 0 ▶ $op->{cb} = sub { shift->ioloop->stop; ($err, $reply) = @_ };
Subroutine __ANON__: not called CC=1 SCAR=6.9
290 0 $self->_next($op);
291 0 $self->ioloop->start;
292 0 ▶ return $err ? croak $err : $reply;
Branch: 1 branch
BranchTrueFalseTotal
$err ? : 0 0 0
293 }
294  
295 0 ▶sub _write {
Subroutine _write: not called CC=14 SCAR=53.5
296 0 my ($self, $id) = @_;
297  
298 # Make sure connection has not been corrupted while event loop was stopped
299 0 my $c = $self->{connections}{$id};
300 0 ▶ return $c->{start} if $c->{last};
Branch: 1 branch
BranchTrueFalseTotal
if $c->{"last"} 0 0 0
301 0 my $loop = $self->_loop($c->{nb});
302 0 ▶ return undef unless my $stream = $loop->stream($id);
Branch: 1 branch
BranchTrueFalseTotal
unless my $stream = $loop->stream($id) 0 0 0
303 0 ▶ if (!$loop->is_running && $stream->is_readable) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $loop->is_running and $stream->is_readable) 0 0 0
Condition0%0/3
not $loop->is_running and $stream->is_readable
!ll&&!rl&&r
000
MC/DC0%0/2
not $loop->is_running and $stream->is_readable
not $loop->is_running $stream->is_readable
Truth table0%0/3
not(A) and B
A= not $loop->is_runningB= $stream->is_readable
ABresult
0X0
100
111
304 0 $stream->close;
305 0 return undef;
306 }
307  
308 # Fast operation
309 0 ▶ delete $c->{start} unless my $last = delete $c->{fast};
Branch: 1 branch
BranchTrueFalseTotal
unless my $last = delete $c->{"fast"} 0 0 0
310  
311 # Blocking operations have a higher precedence
312 return $c->{start}
313 0 ▶ unless $last || ($c->{nb} xor !($self->{queue}->[-1] || {})->{nb});
Branch: 1 branch
BranchTrueFalseTotal
unless $last or ($c->{"nb"} xor not +($self->{"queue"}[-1] || {})->{"nb"}) 0 0 0
Condition0%0/9
$last or ($c->{"nb"} xor not +($self->{"queue"}[-1] || {})->{"nb"})
l!l&&r!l&&!r
000
$c->{"nb"} xor not +($self->{"queue"}[-1] || {})->{"nb"}
l&&rl&&!r!l&&r!l&&!r
0000
$self->{'queue'}[-1] || {}
l!l
00
MC/DC0%0/3
$last or ($c->{"nb"} xor not +($self->{"queue"}[-1] || {})->{"nb"})
$last $c->{"nb"} $self->{'queue'}[-1]
Truth table0%0/5
A or B xor not(C)
A= $lastB= $c->{"nb"}C= $self->{'queue'}[-1]
ABCresult
1XX1
0111
0001
0100
0010
314 0 ▶ $last ||= $c->{nb} ? shift @{$self->{queue}} : pop @{$self->{queue}};
Branch: 1 branch
BranchTrueFalseTotal
$c->{'nb'} ? : 0 0 0
Condition0%0/3
$last ||= $c->{"nb"} ? shift @{$$self{"queue"};} : pop @{$$self{"queue"};}
l!l&&r!l&&!r
000
MC/DC0%0/2
$last ||= $c->{"nb"} ? shift @{$$self{"queue"};} : pop @{$$self{"queue"};}
$last $c->{"nb"} ? shift @{$$self{"queue"};} : pop @{$$self{"queue"};}
Truth table0%0/3
A ||= B
A= $lastB= $c->{"nb"} ? shift @{$$self{"queue"};} : pop @{$$self{"queue"};}
ABresult
1X1
011
000
315  
316 0 ▶ return $c->{start} unless $c->{last} = $last;
Branch: 1 branch
BranchTrueFalseTotal
unless $c->{"last"} = $last 0 0 0
317 0 warn "-- Client >>> Server (#$last->{id})\n" if DEBUG;
318 0 $stream->write(delete $last->{msg});
319  
320 # Unsafe operations are done when they are written
321 0 ▶ return $c->{start} if $last->{safe};
Branch: 1 branch
BranchTrueFalseTotal
if $last->{"safe"} 0 0 0
322 0 weaken $self;
323 0 ▶ $stream->write('', sub { $self->_finish(undef, delete($c->{last})->{cb}) });
Subroutine __ANON__: not called CC=1 SCAR=6.9
324 0 return $c->{start};
325 }
326  
327 9 1;
328  
329 =encoding utf8
330  
331 =head1 NAME
332  
333 Mango - Pure-Perl non-blocking I/O MongoDB driver
334  
335 =head1 SYNOPSIS
336  
337 use Mango;
338 use feature state;
339  
340 # Declare a Mango helper
341 sub mango { state $m = Mango->new('mongodb://localhost:27017') }
342 # or in a Mojolicious::Lite app
343 helper mango => sub { state $m = Mango->new('mongodb://localhost:27017') };
344  
345 # Insert document
346 my $oid = mango->db('test')->collection('foo')->insert({bar => 'baz'});
347  
348 # Find document
349 my $doc = mango->db('test')->collection('foo')->find_one({bar => 'baz'});
350 say $doc->{bar};
351  
352 # Update document
353 mango->db('test')->collection('foo')
354 ->update({bar => 'baz'}, {bar => 'yada'});
355  
356 # Remove document
357 mango->db('test')->collection('foo')->remove({bar => 'yada'});
358  
359 # Insert document with special BSON types
360 use Mango::BSON ':bson';
361 my $oid = mango->db('test')->collection('foo')
362 ->insert({data => bson_bin("\x00\x01"), now => bson_time});
363  
364 # Non-blocking concurrent find
365 my $delay = Mojo::IOLoop->delay(sub {
366 my ($delay, @docs) = @_;
367 ...
368 });
369 for my $name (qw(sri marty)) {
370 my $end = $delay->begin(0);
371 mango->db('test')->collection('users')->find({name => $name})->all(sub {
372 my ($cursor, $err, $docs) = @_;
373 $end->(@$docs);
374 });
375 }
376 $delay->wait;
377  
378 # Event loops such as AnyEvent are supported through EV
379 use EV;
380 use AnyEvent;
381 my $cv = AE::cv;
382 mango->db('test')->command(buildInfo => sub {
383 my ($db, $err, $doc) = @_;
384 $cv->send($doc->{version});
385 });
386 say $cv->recv;
387  
388 =head1 DESCRIPTION
389  
390 L<Mango> is a pure-Perl non-blocking I/O MongoDB driver, optimized for use
391 with the L<Mojolicious> real-time web framework, and with multiple event loop
392 support. Since MongoDB is still changing rapidly, only the latest stable
393 version is supported.
394  
395 For MongoDB 2.6 support, use L<Mango> 1.16.
396  
397 To learn more about MongoDB you should take a look at the
398 L<official documentation|http://docs.mongodb.org>, the documentation included
399 in this distribution is no replacement for it.
400  
401 Look at L<Mango::Collection> for CRUD operations.
402  
403 Many arguments passed to methods as well as values of attributes get
404 serialized to BSON with L<Mango::BSON>, which provides many helper functions
405 you can use to generate data types that are not available natively in Perl.
406 All connections will be reset automatically if a new process has been forked,
407 this allows multiple processes to share the same L<Mango> object safely.
408  
409 For better scalability (epoll, kqueue) and to provide IPv6, SOCKS5 as well as
410 TLS support, the optional modules L<EV> (4.0+), L<IO::Socket::IP> (0.20+),
411 L<IO::Socket::Socks> (0.64+) and L<IO::Socket::SSL> (1.84+) will be used
412 automatically if they are installed. Individual features can also be disabled
413 with the C<MOJO_NO_IPV6>, C<MOJO_NO_SOCKS> and C<MOJO_NO_TLS> environment
414 variables.
415  
416 =head1 EVENTS
417  
418 L<Mango> inherits all events from L<Mojo::EventEmitter> and can emit the
419 following new ones.
420  
421 =head2 connection
422  
423 $mango->on(connection => sub {
424 my ($mango, $id) = @_;
425 ...
426 });
427  
428 Emitted when a new connection has been established.
429  
430 =head1 ATTRIBUTES
431  
432 L<Mango> implements the following attributes.
433  
434 =head2 default_db
435  
436 my $name = $mango->default_db;
437 $mango = $mango->default_db('test');
438  
439 Default database, defaults to C<admin>.
440  
441 =head2 hosts
442  
443 my $hosts = $mango->hosts;
444 $mango = $mango->hosts([['localhost', 3000], ['localhost', 4000]]);
445  
446 Servers to connect to, defaults to C<localhost> and port C<27017>.
447  
448 =head2 inactivity_timeout
449  
450 my $timeout = $mango->inactivity_timeout;
451 $mango = $mango->inactivity_timeout(15);
452  
453 Maximum amount of time in seconds a connection can be inactive before getting
454 closed, defaults to C<0>. Setting the value to C<0> will allow connections to
455 be inactive indefinitely.
456  
457 =head2 ioloop
458  
459 my $loop = $mango->ioloop;
460 $mango = $mango->ioloop(Mojo::IOLoop->new);
461  
462 Event loop object to use for blocking I/O operations, defaults to a
463 L<Mojo::IOLoop> object.
464  
465 =head2 j
466  
467 my $j = $mango->j;
468 $mango = $mango->j(1);
469  
470 Wait for all operations to have reached the journal, defaults to C<0>.
471  
472 =head2 max_bson_size
473  
474 my $max = $mango->max_bson_size;
475 $mango = $mango->max_bson_size(16777216);
476  
477 Maximum size for BSON documents in bytes, defaults to C<16777216> (16MB).
478  
479 =head2 max_connections
480  
481 my $max = $mango->max_connections;
482 $mango = $mango->max_connections(5);
483  
484 Maximum number of connections to use for non-blocking operations, defaults to
485 C<5>.
486  
487 =head2 max_write_batch_size
488  
489 my $max = $mango->max_write_batch_size;
490 $mango = $mango->max_write_batch_size(1000);
491  
492 Maximum number of write operations to batch together, defaults to C<1000>.
493  
494 =head2 protocol
495  
496 my $protocol = $mango->protocol;
497 $mango = $mango->protocol(Mango::Protocol->new);
498  
499 Protocol handler, defaults to a L<Mango::Protocol> object.
500  
501 =head2 w
502  
503 my $w = $mango->w;
504 $mango = $mango->w(2);
505  
506 Wait for all operations to have reached at least this many servers, C<1>
507 indicates just primary, C<2> indicates primary and at least one secondary,
508 defaults to C<1>.
509  
510 =head2 wtimeout
511  
512 my $timeout = $mango->wtimeout;
513 $mango = $mango->wtimeout(1);
514  
515 Timeout for write propagation in milliseconds, defaults to C<1000>.
516  
517 =head1 METHODS
518  
519 L<Mango> inherits all methods from L<Mojo::Base> and implements the following
520 new ones.
521  
522 =head2 backlog
523  
524 my $num = $mango->backlog;
525  
526 Number of queued operations that have not yet been assigned to a connection.
527  
528 =head2 db
529  
530 my $db = $mango->db;
531 my $db = $mango->db('test');
532  
533 Build L<Mango::Database> object for database, uses L</"default_db"> if no name
534 is provided. Note that the reference L<Mango::Database/"mango"> is weakened,
535 so the L<Mango> object needs to be referenced elsewhere as well.
536  
537 =head2 from_string
538  
539 $mango
540 = $mango->from_string('mongodb://sri:s3cret@localhost:3000/test?w=2');
541  
542 Parse configuration from connection string.
543  
544 =head2 get_more
545  
546 my $reply = $mango->get_more($namespace, $return, $cursor);
547  
548 Perform low level C<GET_MORE> operation. You can also append a callback to
549 perform operation non-blocking.
550  
551 $mango->get_more(($namespace, $return, $cursor) => sub {
552 my ($mango, $err, $reply) = @_;
553 ...
554 });
555 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
556  
557 =head2 kill_cursors
558  
559 $mango->kill_cursors(@ids);
560  
561 Perform low level C<KILL_CURSORS> operation. You can also append a callback to
562 perform operation non-blocking.
563  
564 $mango->kill_cursors(@ids => sub {
565 my ($mango, $err) = @_;
566 ...
567 });
568 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
569  
570 =head2 new
571  
572 my $mango = Mango->new;
573 my $mango = Mango->new('mongodb://sri:s3cret@localhost:3000/test?w=2');
574  
575 # Using TLS encryption
576 my $mango = Mango->new('mongodb://127.0.0.1:27017', tls => 1,
577 tls_cert => '/path/to/certificate.pem');
578  
579 Construct a new L<Mango> object and parse connection string with
580 L</"from_string"> if necessary.
581  
582 Not that is is B<strongly> recommended to build your Mango object inside
583 a helper function like shown in the synopsis. This is because the Mango's
584 object reference inside L<Mango::Database> objects is weakened to avoid
585 memory leaks. This means your Mango instance is quickly going to get
586 undefined after you use the C<db> method. So, use a helper to prevent that.
587  
588 If a username and password are provided, Mango will try to authenticate using
589 SCRAM-SHA1. B<Warning:> this will require L<Authen::SCRAM> which is not
590 installed by default.
591  
592 Any extra arguments given after the connection string will be passed to the
593 C<connect> method from L<Mojo::IOLoop::Client>. To connect to a server using
594 TLS, use the options C<tls> (boolean), C<tls_cert> and optionally C<tls_ca>.
595  
596 =head2 query
597  
598 my $reply
599 = $mango->query($namespace, $flags, $skip, $return, $query, $fields);
600  
601 Perform low level C<QUERY> operation. You can also append a callback to
602 perform operation non-blocking.
603  
604 $mango->query(($namespace, $flags, $skip, $return, $query, $fields) => sub {
605 my ($mango, $err, $reply) = @_;
606 ...
607 });
608 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
609  
610 =head1 DEBUGGING
611  
612 You can set the C<MANGO_DEBUG> environment variable to get some advanced
613 diagnostics information printed to C<STDERR>.
614  
615 MANGO_DEBUG=1
616  
617 =head1 SPONSORS
618  
619 Some of the work on this distribution has been sponsored by
620 L<Drip Depot|http://www.dripdepot.com>, thank you!
621  
622 =head1 AUTHOR
623  
624 Sebastian Riedel, C<sri@cpan.org>.
625  
626 Current maintainer: Olivier Duclos C<odc@cpan.org>.
627  
628 =head1 CREDITS
629  
630 In alphabetical order:
631  
632 =over 2
633  
634 alexbyk
635  
636 Andrey Khozov
637  
638 Colin Cyr
639  
640 =back
641  
642 =head1 COPYRIGHT AND LICENSE
643  
644 Copyright (C) 2013-2014, Sebastian Riedel.
645  
646 This program is free software, you can redistribute it and/or modify it under
647 the terms of the Artistic License version 2.0.
648  
649 =head1 SEE ALSO
650  
651 L<https://github.com/oliwer/mango>, L<Mojolicious::Guides>,
652 L<http://mojolicio.us>.
653  
654 =cut
↑ Summary Mango/Cursor/Query.pm »