Mojo/UserAgent.pm

filter: Statementstmt 82.2% 217 / 264 Branchbran 53.6% 59 / 110 Conditioncond 45.7% 43 / 94 MC/DCmcdc 10.8% 5 / 46 Subroutinesub 75.0% 48 / 64 Podpod 100% 6 / 6 totaltotal 64.7% 378 / 584 CC 97 SCAR 20.5
CC
97
Cov
68%
__ANON__
30.0
_finish
24.1
_start
18.2
CRAP 7.8
« Mojo/Util.pm ↑ Summary Mojo/IOLoop/Client.pm »
1 package Mojo::UserAgent;
2 23 ▶use Mojo::Base 'Mojo::EventEmitter';
Subroutine BEGIN: called CC=1 SCAR=0.0
3  
4 # "Fry: Since when is the Internet about robbing people of their privacy?
5 # Bender: August 6, 1991."
6 23 ▶use Mojo::IOLoop;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 23 ▶use Mojo::Promise;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 23 ▶use Mojo::Util qw(monkey_patch term_escape);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 23 ▶use Mojo::UserAgent::CookieJar;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 23 ▶use Mojo::UserAgent::Proxy;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 23 ▶use Mojo::UserAgent::Server;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 23 ▶use Mojo::UserAgent::Transactor;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 23 ▶use Scalar::Util qw(weaken);
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 23 ▶use constant DEBUG => $ENV{MOJO_CLIENT_DEBUG} || 0;
Subroutine BEGIN: called CC=2 SCAR=7.1
Condition50%1/2
$ENV{'MOJO_CLIENT_DEBUG'} || 0
l!l
023
MC/DC0%0/1
$ENV{'MOJO_CLIENT_DEBUG'} || 0
$ENV{'MOJO_CLIENT_DEBUG'}
Truth table50%1/2
A
A= $ENV{'MOJO_CLIENT_DEBUG'}
Aresult
11
00
16  
17 0 ▶has ca => sub { $ENV{MOJO_CA_FILE} };
Subroutine __ANON__: not called CC=1 SCAR=1.2
18 0 ▶has cert => sub { $ENV{MOJO_CERT_FILE} };
Subroutine __ANON__: not called CC=1 SCAR=1.2
19 17 ▶has connect_timeout => sub { $ENV{MOJO_CONNECT_TIMEOUT} || 10 };
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
$ENV{"MOJO_CONNECT_TIMEOUT"} or 10 0 17 17
20 17 ▶has cookie_jar => sub { Mojo::UserAgent::CookieJar->new };
Subroutine __ANON__: called CC=1 SCAR=0.0
21 17 ▶has inactivity_timeout => sub { $ENV{MOJO_INACTIVITY_TIMEOUT} // 40 };
Subroutine __ANON__: called CC=2 SCAR=7.2
Condition50%1/2
$ENV{"MOJO_INACTIVITY_TIMEOUT"} // 40
l!l
017
MC/DC0%0/1
$ENV{"MOJO_INACTIVITY_TIMEOUT"} // 40
$ENV{"MOJO_INACTIVITY_TIMEOUT"}
Truth table50%1/2
A
A= $ENV{"MOJO_INACTIVITY_TIMEOUT"}
Aresult
11
00
22 0 ▶has insecure => sub { $ENV{MOJO_INSECURE} };
Subroutine __ANON__: not called CC=1 SCAR=1.2
23 23 has 'max_response_size';
24 4 ▶has ioloop => sub { Mojo::IOLoop->new };
Subroutine __ANON__: called CC=1 SCAR=0.0
25 0 ▶has key => sub { $ENV{MOJO_KEY_FILE} };
Subroutine __ANON__: not called CC=1 SCAR=1.2
26 23 has max_connections => 5;
27 0 ▶has max_redirects => sub { $ENV{MOJO_MAX_REDIRECTS} || 0 };
Subroutine __ANON__: not called CC=2 SCAR=13.0
Branch: 1 branch
BranchTrueFalseTotal
$ENV{"MOJO_MAX_REDIRECTS"} or 0 0 0 0
28 17 ▶has proxy => sub { Mojo::UserAgent::Proxy->new };
Subroutine __ANON__: called CC=1 SCAR=0.0
29 17 ▶has request_timeout => sub { $ENV{MOJO_REQUEST_TIMEOUT} // 0 };
Subroutine __ANON__: called CC=2 SCAR=7.2
Condition50%1/2
$ENV{"MOJO_REQUEST_TIMEOUT"} // 0
l!l
017
MC/DC0%0/1
$ENV{"MOJO_REQUEST_TIMEOUT"} // 0
$ENV{"MOJO_REQUEST_TIMEOUT"}
Truth table50%1/2
A
A= $ENV{"MOJO_REQUEST_TIMEOUT"}
Aresult
11
00
30 29 ▶has server => sub { Mojo::UserAgent::Server->new(ioloop => shift->ioloop) };
Subroutine __ANON__: called CC=1 SCAR=0.0
31 17 ▶has [qw(socket_options tls_options)] => sub { {} };
Subroutine __ANON__: called CC=1 SCAR=0.0
32 17 ▶has transactor => sub { Mojo::UserAgent::Transactor->new };
Subroutine __ANON__: called CC=1 SCAR=0.0
33  
34 # Common HTTP methods
35 23 for my $name (qw(DELETE GET HEAD OPTIONS PATCH POST PUT QUERY)) {
36 13 ▶ monkey_patch __PACKAGE__, lc $name, sub {
Subroutine delete: called CC=2 SCAR=7.2
Subroutine query: called CC=2 SCAR=7.2
37 13 ▶ my ($self, $cb) = (shift, ref $_[-1] eq 'CODE' ? pop : undef);
Branch: 2 branches
BranchTrueFalseTotal
ref $_[-1] eq 'CODE' ? : 0 13 13
ref $_[-1] eq 'CODE' ? : 0 2 2
38 13 return $self->start($self->build_tx($name, @_), $cb);
39 184 };
40 3 ▶ monkey_patch __PACKAGE__, lc($name) . '_p', sub {
Subroutine __ANON__: called CC=1 SCAR=1.2
Subroutine options_p: not called CC=1 SCAR=1.2
41 0 my $self = shift;
42 0 return $self->start_p($self->build_tx($name, @_));
43 184 };
44 }
45  
46 26 ▶sub DESTROY { shift->_cleanup unless ${^GLOBAL_PHASE} eq 'DESTRUCT' }
Subroutine DESTROY: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
unless ${^GLOBAL_PHASE} eq "DESTRUCT" 26 0 26
47  
48 162 ▶sub build_tx { shift->transactor->tx(@_) }
Subroutine build_tx: called CC=1 SCAR=0.0
Pod documented
49 1 ▶sub build_websocket_tx { shift->transactor->websocket(@_) }
Subroutine build_websocket_tx: called CC=1 SCAR=0.0
Pod documented
50  
51 160 ▶sub start {
Subroutine start: called CC=5 SCAR=16.2
Pod documented
52 160 my ($self, $tx, $cb) = @_;
53  
54 # Fork-safety
55 160 ▶ $self->_cleanup->server->restart if $self->{pid} && $self->{pid} ne $$;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"pid"} and $self->{"pid"} ne $$ 0 160 160
Condition66%2/3
$self->{"pid"} and $self->{"pid"} ne $$
!ll&&!rl&&r
171430
MC/DC0%0/2
$self->{"pid"} and $self->{"pid"} ne $$
$self->{"pid"} $self->{"pid"} ne $$
Truth table66%2/3
A and B
A= $self->{"pid"}B= $self->{"pid"} ne $$
ABresult
0X0
100
111
56 160 ▶ $self->{pid} //= $$;
Condition66%2/3
$self->{"pid"} //= $$
l!l&&r!l&&!r
143170
MC/DC0%0/2
$self->{"pid"} //= $$
$self->{"pid"} $$
Truth table66%2/3
A //= B
A= $self->{"pid"}B= $$
ABresult
1X1
011
000
57  
58 # Non-blocking
59 160 ▶ if ($cb) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cb) 4 156 160
60 4 warn "-- Non-blocking request (@{[_url($tx)]})\n" if DEBUG;
61 4 return $self->_start(Mojo::IOLoop->singleton, $tx, $cb);
62 }
63  
64 # Blocking
65 156 warn "-- Blocking request (@{[_url($tx)]})\n" if DEBUG;
66 156 ▶ $self->_start($self->ioloop, $tx => sub { shift->ioloop->stop; $tx = shift });
Subroutine __ANON__: called CC=1 SCAR=0.0
67 156 $self->ioloop->start;
68  
69 156 return $tx;
70 }
71  
72 3 ▶sub start_p {
Subroutine start_p: called CC=1 SCAR=0.0
Pod documented
73 3 my ($self, $tx) = @_;
74 3 my $promise = Mojo::Promise->new;
75 3 ▶ $self->start($tx => sub { shift->transactor->promisify($promise, shift) });
Subroutine __ANON__: called CC=1 SCAR=0.0
76 3 return $promise;
77 }
78  
79 0 ▶sub websocket {
Subroutine websocket: not called CC=1 SCAR=6.9
Pod documented
80 0 my ($self, $cb) = (shift, pop);
81 0 $self->start($self->build_websocket_tx(@_), $cb);
82 }
83  
84 0 ▶sub websocket_p {
Subroutine websocket_p: not called CC=1 SCAR=6.9
Pod documented
85 0 my $self = shift;
86 0 return $self->start_p($self->build_websocket_tx(@_));
87 }
88  
89 26 ▶sub _cleanup {
Subroutine _cleanup: called CC=3 SCAR=11.0
90 26 my $self = shift;
91 26 delete $self->{pid};
92 26 ▶ $self->_finish($_, 1, 1) for keys %{$self->{connections} // {}};
Condition100%2/2
$self->{"connections"} // {}
l!l
1412
MC/DC100%1/1
$self->{"connections"} // {}
$self->{"connections"}
Truth table100%2/2
A
A= $self->{"connections"}
Aresult
11
00
93 26 return $self;
94 }
95  
96 24 ▶sub _connect {
Subroutine _connect: called CC=8 SCAR=26.2
97 24 my ($self, $loop, $tx, $handle) = @_;
98  
99 24 my $t = $self->transactor;
100 24 ▶ my ($proto, $host, $port) = $handle ? $t->endpoint($tx) : $t->peer($tx);
Branch: 1 branch
BranchTrueFalseTotal
$handle ? : 0 24 24
101  
102 24 my %options = (timeout => $self->connect_timeout);
103 0 ▶ if ($proto eq 'http+unix') { $options{path} = $host }
Branch: 1 branch
BranchTrueFalseTotal
if ($proto eq 'http+unix') { } 0 24 24
104 24 else { @options{qw(address port)} = ($host, $port) }
105 24 $options{socket_options} = $self->socket_options;
106 24 ▶ $options{handle} = $handle if $handle;
Branch: 1 branch
BranchTrueFalseTotal
if $handle 0 24 24
107  
108 # SOCKS
109 24 ▶ if ($proto eq 'socks') {
Branch: 1 branch
BranchTrueFalseTotal
if ($proto eq "socks") 0 24 24
110 0 @options{qw(socks_address socks_port)} = @options{qw(address port)};
111 0 ($proto, @options{qw(address port)}) = $t->endpoint($tx);
112 0 my $userinfo = $tx->req->via_proxy(0)->proxy->userinfo;
113 0 ▶ @options{qw(socks_user socks_pass)} = split /:/, $userinfo if $userinfo;
Branch: 1 branch
BranchTrueFalseTotal
if $userinfo 0 0 0
114 }
115  
116 # TLS
117 24 ▶ if ($options{tls} = $proto eq 'https') {
Branch: 1 branch
BranchTrueFalseTotal
if ($options{"tls"} = $proto eq "https") 0 24 24
118 0 map { $options{"tls_$_"} = $self->$_ } qw(ca cert key);
119 0 $options{tls_options} = $self->tls_options;
120 0 ▶ $options{tls_options}{SSL_verify_mode} = 0x00 if $self->insecure;
Branch: 1 branch
BranchTrueFalseTotal
if $self->insecure 0 0 0
121 }
122  
123 24 weaken $self;
124 24 my $id;
125 return $id = $loop->client(
126 24 ▶ %options => sub {
Subroutine __ANON__: called CC=3 SCAR=12.2
127 24 my ($loop, $err, $stream) = @_;
128  
129 # Connection error
130 24 ▶ return unless $self;
Branch: 1 branch
BranchTrueFalseTotal
unless $self 0 24 24
131 24 ▶ return $self->_error($id, $err) if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 24 24
132  
133 # Connection established
134 0 ▶ $stream->on(timeout => sub { $self->_error($id, 'Inactivity timeout') });
Subroutine __ANON__: not called CC=1 SCAR=1.2
135 24 ▶ $stream->on(close => sub { $self && $self->_finish($id, 1) });
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
$self and $self->_finish($id, 1) 21 0 21
136 0 ▶ $stream->on(error => sub { $self && $self->_error($id, pop) });
Subroutine __ANON__: not called CC=2 SCAR=13.0
Branch: 1 branch
BranchTrueFalseTotal
$self and $self->_error($id, pop()) 0 0 0
137 24 ▶ $stream->on(read => sub { $self->_read($id, pop) });
Subroutine __ANON__: called CC=1 SCAR=0.0
138 24 $self->_process($id);
139 }
140 24 );
141 }
142  
143 24 ▶sub _connect_proxy {
Subroutine _connect_proxy: called CC=2 SCAR=15.5
144 24 my ($self, $loop, $old, $cb) = @_;
145  
146 # Start CONNECT request
147 24 ▶ return undef unless my $new = $self->transactor->proxy_connect($old);
Branch: 1 branch
BranchTrueFalseTotal
unless my $new = $self->transactor->proxy_connect($old) 24 0 24
148 0 my $id;
149 return $id = $self->_start(
150 0 ▶ ($loop, $new) => sub {
Subroutine __ANON__: not called CC=5 SCAR=34.0
151 0 my ($self, $tx) = @_;
152  
153 # Real transaction
154 0 $old->previous($tx)->req->via_proxy(0);
155 0 my $c = $self->{connections}{$id} = {cb => $cb, ioloop => $loop, tx => $old};
156  
157 # CONNECT failed
158 0 ▶ return $self->_error($id, 'Proxy connection failed') if $tx->error || !$tx->res->is_success || !$tx->keep_alive;
Branch: 1 branch
BranchTrueFalseTotal
if $tx->error or not $tx->res->is_success or not $tx->keep_alive 0 0 0
Condition0%0/6
$tx->error or not $tx->res->is_success or not $tx->keep_alive
l!l&&r!l&&!r
000
$tx->error or not $tx->res->is_success
l!l&&r!l&&!r
000
MC/DC0%0/3
$tx->error or not $tx->res->is_success or not $tx->keep_alive
$tx->error not $tx->res->is_success not $tx->keep_alive
Truth table0%0/4
A or not(B) or not(C)
A= $tx->errorB= not $tx->res->is_successC= not $tx->keep_alive
ABCresult
1XX1
01X1
0011
0000
159  
160 # Start real transaction without TLS upgrade
161 0 ▶ return $self->_process($id) unless $tx->req->url->protocol eq 'https';
Branch: 1 branch
BranchTrueFalseTotal
unless $tx->req->url->protocol eq "https" 0 0 0
162  
163 # TLS upgrade before starting the real transaction
164 0 my $handle = $loop->stream($id)->steal_handle;
165 0 $self->_remove($id);
166 0 $id = $self->_connect($loop, $old, $handle);
167 0 $self->{connections}{$id} = $c;
168 }
169 0 );
170 }
171  
172 160 ▶sub _connection {
Subroutine _connection: called CC=8 SCAR=23.8
173 160 my ($self, $loop, $tx, $cb) = @_;
174  
175 # Reuse connection
176 160 my ($proto, $host, $port) = $self->transactor->endpoint($tx);
177 160 my $id;
178 160 ▶ if ($id = $self->_dequeue($loop, "$proto:$host:$port", 1)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($id = $self->_dequeue($loop, "${proto}:${host}:$port", 1)) 136 24 160
179 136 warn "-- Reusing connection $id ($proto://$host:$port)\n" if DEBUG;
180 136 @{$self->{connections}{$id}}{qw(cb tx)} = ($cb, $tx);
181 136 ▶ $tx->kept_alive(1) unless $tx->connection;
Branch: 1 branch
BranchTrueFalseTotal
unless $tx->connection 136 0 136
182 136 $self->_process($id);
183 136 return $id;
184 }
185  
186 # CONNECT request to proxy required
187 0 ▶ if (my $id = $self->_connect_proxy($loop, $tx, $cb)) { return $id }
Branch: 1 branch
BranchTrueFalseTotal
if (my $id = $self->_connect_proxy($loop, $tx, $cb)) 0 24 24
188  
189 # New connection
190 0 ▶ $tx->res->error({message => "Unsupported protocol: $proto"}) and return $loop->next_tick(sub { $self->$cb($tx) })
Subroutine __ANON__: not called CC=1 SCAR=6.9
191 24 ▶ unless $proto eq 'http' || $proto eq 'https' || $proto eq 'http+unix';
Branch: 1 branch
BranchTrueFalseTotal
unless $proto eq "http" or $proto eq "https" or $proto eq "http+unix" 0 24 24
Condition27%3/11
$proto eq 'http' || $proto eq 'https' || $proto eq 'http+unix' || $tx->res->error({'message', "Unsupported protocol: $proto"}) && (return $loop->next_tick(sub { $self->$cb($tx); } ))
l!l&&r!l&&!r
2400
$proto eq "http" or $proto eq "https" or $proto eq "http+unix"
l!l&&r!l&&!r
2400
$proto eq "http" or $proto eq "https"
l!l&&r!l&&!r
2400
$tx->res->error({"message", "Unsupported protocol: $proto"}) and return $loop->next_tick(sub { $self->$cb($tx); } )
!ll
00
MC/DC0%0/4
$proto eq 'http' || $proto eq 'https' || $proto eq 'http+unix' || $tx->res->error({'message', "Unsupported protocol: $proto"}) && (return $loop->next_tick(sub { $self->$cb($tx); } ))
$proto eq "http" $proto eq "https" $proto eq "http+unix" $tx->res->error({"message", "Unsupported protocol: $proto"})
Truth table20%1/5
A or B or C || D
A= $proto eq "http"B= $proto eq "https"C= $proto eq "http+unix"D= $tx->res->error({"message", "Unsupported protocol: $proto"})
ABCDresult
1XXX1
01XX1
001X1
00011
00000
192 24 $id = $self->_connect($loop, $tx);
193 24 warn "-- Connect $id ($proto://$host:$port)\n" if DEBUG;
194 24 $self->{connections}{$id} = {cb => $cb, ioloop => $loop, tx => $tx};
195  
196 24 return $id;
197 }
198  
199 182 ▶sub _dequeue {
Subroutine _dequeue: called CC=9 SCAR=22.4
200 182 my ($self, $loop, $name, $test) = @_;
201  
202 182 ▶ my $old = $self->{queue}{$loop} //= [];
Condition100%2/2
$self->{"queue"}{$loop} //= []
l!l
16517
MC/DC100%1/1
$self->{"queue"}{$loop} //= []
$self->{"queue"}{$loop}
Truth table100%2/2
A
A= $self->{"queue"}{$loop}
Aresult
11
00
203 182 my ($found, @new);
204 182 for my $queued (@$old) {
205 177 ▶ push @new, $queued and next if $found || !grep { $_ eq $name } @$queued;
Branch: 1 branch
BranchTrueFalseTotal
if $found or not grep({$_ eq $name;} @$queued) 24 153 177
Condition75%6/8
($found || !grep({$_ eq $name;} @$queued)) && (push(@new, $queued) && (next))
!ll
153240
$found or not grep({$_ eq $name;} @$queued)
l!l&&r!l&&!r
816153
push @new, $queued and next
!ll
024
MC/DC0%0/3
($found || !grep({$_ eq $name;} @$queued)) && (push(@new, $queued) && (next))
$found not grep({$_ eq $name;} @$queued) push @new, $queued
Truth table20%1/5
A or not(B) && C
A= $foundB= not grep({$_ eq $name;} @$queued)C= push @new, $queued
ABCresult
00X0
1X00
0100
1X11
0111
206  
207 # Search for id/name and sort out corrupted connections if necessary
208 153 ▶ next unless my $stream = $loop->stream($queued->[1]);
Branch: 1 branch
BranchTrueFalseTotal
unless my $stream = $loop->stream($queued->[1]) 0 153 153
209 153 ▶ $test && $stream->is_readable ? $stream->close : ($found = $queued->[1]);
Branch: 1 branch
BranchTrueFalseTotal
$test && $stream->is_readable ? : 0 153 153
Condition66%2/3
$test and $stream->is_readable
!ll&&!rl&&r
171360
MC/DC0%0/2
$test and $stream->is_readable
$test $stream->is_readable
Truth table66%2/3
A and B
A= $testB= $stream->is_readable
ABresult
0X0
100
111
210 }
211 182 @$old = @new;
212  
213 182 return $found;
214 }
215  
216 0 ▶sub _error {
Subroutine _error: not called CC=2 SCAR=17.9
217 0 my ($self, $id, $err) = @_;
218 0 my $tx = $self->{connections}{$id}{tx};
219 0 ▶ $tx->res->error({message => $err}) if $tx;
Branch: 1 branch
BranchTrueFalseTotal
if $tx 0 0 0
220 0 $self->_finish($id, 1);
221 }
222  
223 199 ▶sub _finish {
Subroutine _finish: called CC=16 SCAR=31.8
224 199 my ($self, $id, $close, $local) = @_;
225  
226 # Remove request timeout and finish transaction
227 199 ▶ return undef unless my $c = $self->{connections}{$id};
Branch: 1 branch
BranchTrueFalseTotal
unless my $c = $self->{"connections"}{$id} 21 178 199
228 178 ▶ $c->{ioloop}->remove(delete $c->{timeout}) if $c->{timeout};
Branch: 1 branch
BranchTrueFalseTotal
if $c->{"timeout"} 0 178 178
229 178 ▶ return $self->_reuse($id, $close) unless my $old = $c->{tx};
Branch: 1 branch
BranchTrueFalseTotal
unless my $old = $c->{"tx"} 17 161 178
230  
231 # Premature connection close (RFC 9112 8: only close-delimited bodies may end with the server closing the connection)
232 161 my $res = $old->res;
233 161 my $content = $res->content;
234 161 ▶ my $premature = !$res->code || (!$res->is_finished && ($local || $content->is_chunked || !$content->relaxed));
Condition16%2/12
!$res->code || !$res->is_finished && ($local || $content->is_chunked || !$content->relaxed)
l!l&&r!l&&!r
00161
not $res->is_finished and $local || $content->is_chunked || !$content->relaxed
!ll&&!rl&&r
16100
$local or $content->is_chunked or not $content->relaxed
l!l&&r!l&&!r
000
$local or $content->is_chunked
l!l&&r!l&&!r
000
MC/DC0%0/5
!$res->code || !$res->is_finished && ($local || $content->is_chunked || !$content->relaxed)
!$res->code not $res->is_finished $local $content->is_chunked not $content->relaxed
Truth table16%1/6
not(A) || not(B) and C or D or not(E)
A= !$res->codeB= not $res->is_finishedC= $localD= $content->is_chunkedE= not $content->relaxed
ABCDEresult
1XXXX1
011XX1
0101X1
010011
00XXX0
010000
235 161 ▶ $res->error({message => 'Premature connection close'}) if $close && $premature && !$res->error;
Branch: 1 branch
BranchTrueFalseTotal
if $close and $premature and not $res->error 0 161 161
Condition33%2/6
$close and $premature and not $res->error
!ll&&!rl&&r
16100
$close and $premature
!ll&&!rl&&r
16100
MC/DC0%0/3
$close and $premature and not $res->error
$close $premature not $res->error
Truth table25%1/4
A and B and not(C)
A= $closeB= $prematureC= not $res->error
ABCresult
0XX0
10X0
1100
1111
236  
237 # Finish events need to see the error
238 161 $res->finish;
239 161 $old->closed;
240  
241 # Always remove connection for WebSockets
242 161 ▶ return $self->_remove($id) if $old->is_websocket;
Branch: 1 branch
BranchTrueFalseTotal
if $old->is_websocket 1 160 161
243 160 $self->cookie_jar->collect($old);
244  
245 # Upgrade connection to WebSocket
246 160 ▶ if (my $new = $self->transactor->upgrade($old)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $new = $self->transactor->upgrade($old)) 1 159 160
247 1 weaken $self;
248 1 ▶ $new->on(resume => sub { $self->_write($id) });
Subroutine __ANON__: called CC=1 SCAR=0.0
249 1 $c->{cb}($self, $c->{tx} = $new);
250 1 return $new->client_read($old->res->content->leftovers);
251 }
252  
253 # CONNECT requests always have a follow-up request
254 159 ▶ $self->_reuse($id, $close) unless uc $old->req->method eq 'CONNECT';
Branch: 1 branch
BranchTrueFalseTotal
unless uc $old->req->method eq "CONNECT" 159 0 159
255 159 ▶ $res->error({message => $res->message, code => $res->code}) if $res->is_error;
Branch: 1 branch
BranchTrueFalseTotal
if $res->is_error 48 111 159
256 159 ▶ $c->{cb}($self, $old) unless $self->_redirect($c, $old);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_redirect($c, $old) 159 0 159
257 }
258  
259 160 ▶sub _process {
Subroutine _process: called CC=2 SCAR=7.0
260 160 my ($self, $id) = @_;
261  
262 160 my $c = $self->{connections}{$id};
263 160 my $stream = $c->{ioloop}->stream($id)->timeout($self->inactivity_timeout);
264 160 my $tx = $c->{tx}->connection($id);
265 160 my $handle = $stream->handle;
266 160 ▶ unless ($handle->isa('IO::Socket::UNIX')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($handle->isa("IO::Socket::UNIX")) 160 0 160
267 160 $tx->local_address($handle->sockhost)->local_port($handle->sockport);
268 160 $tx->remote_address($handle->peerhost)->remote_port($handle->peerport);
269 }
270  
271 160 weaken $self;
272 0 ▶ $tx->on(resume => sub { $self->_write($id) });
Subroutine __ANON__: not called CC=1 SCAR=1.2
273 160 $self->_write($id);
274 }
275  
276 175 ▶sub _read {
Subroutine _read: called CC=3 SCAR=11.0
277 175 my ($self, $id, $chunk) = @_;
278  
279 # Corrupted connection
280 175 ▶ return $self->_remove($id) unless my $tx = $self->{connections}{$id}{tx};
Branch: 1 branch
BranchTrueFalseTotal
unless my $tx = $self->{"connections"}{$id}{"tx"} 0 175 175
281 175 warn term_escape "-- Client <<< Server (@{[_url($tx)]})\n$chunk\n" if DEBUG;
282 175 $tx->client_read($chunk);
283 175 ▶ $self->_finish($id) if $tx->is_finished;
Branch: 1 branch
BranchTrueFalseTotal
if $tx->is_finished 161 14 175
284 }
285  
286 159 ▶sub _redirect {
Subroutine _redirect: called CC=3 SCAR=17.3
287 159 my ($self, $c, $old) = @_;
288 159 ▶ return undef unless my $new = $self->transactor->redirect($old);
Branch: 1 branch
BranchTrueFalseTotal
unless my $new = $self->transactor->redirect($old) 159 0 159
289 0 ▶ return undef unless @{$old->redirects} < $self->max_redirects;
Branch: 1 branch
BranchTrueFalseTotal
unless @{$old->redirects;} < $self->max_redirects 0 0 0
290 0 return $self->_start($c->{ioloop}, $new, delete $c->{cb});
291 }
292  
293 22 ▶sub _remove {
Subroutine _remove: called CC=2 SCAR=7.0
294 22 my ($self, $id) = @_;
295 22 my $c = delete $self->{connections}{$id};
296 22 ▶ return unless $c->{ioloop};
Branch: 1 branch
BranchTrueFalseTotal
unless $c->{"ioloop"} 0 22 22
297 22 $self->_dequeue($c->{ioloop}, $id);
298 22 $c->{ioloop}->remove($id);
299 }
300  
301 176 ▶sub _reuse {
Subroutine _reuse: called CC=9 SCAR=22.7
302 176 my ($self, $id, $close) = @_;
303  
304 # Connection close
305 176 my $c = $self->{connections}{$id};
306 176 my $tx = delete $c->{tx};
307 176 my $max = $self->max_connections;
308 176 ▶ return $self->_remove($id) if $close || !$tx || !$max || !$tx->keep_alive || $tx->error;
Branch: 1 branch
BranchTrueFalseTotal
if $close or not $tx or not $max or not $tx->keep_alive or $tx->error 21 155 176
Condition75%9/12
$close or not $tx or not $max or not $tx->keep_alive or $tx->error
l!l&&r!l&&!r
210155
$close or not $tx or not $max or not $tx->keep_alive
l!l&&r!l&&!r
174155
$close or not $tx or not $max
l!l&&r!l&&!r
170159
$close or not $tx
l!l&&r!l&&!r
170159
MC/DC40%2/5
$close or not $tx or not $max or not $tx->keep_alive or $tx->error
$close not $tx not $max not $tx->keep_alive $tx->error
Truth table50%3/6
A or not(B) or not(C) or not(D) or E
A= $closeB= not $txC= not $maxD= not $tx->keep_aliveE= $tx->error
ABCDEresult
1XXXX1
01XXX1
001XX1
0001X1
000011
000000
309  
310 # Keep connection alive
311 155 ▶ my $queue = $self->{queue}{$c->{ioloop}} //= [];
Condition50%1/2
$self->{"queue"}{$c->{"ioloop"}} //= []
l!l
1550
MC/DC0%0/1
$self->{"queue"}{$c->{"ioloop"}} //= []
$self->{"queue"}{$c->{"ioloop"}}
Truth table50%1/2
A
A= $self->{"queue"}{$c->{"ioloop"}}
Aresult
11
00
312 155 ▶ $self->_remove(shift(@$queue)->[1]) while @$queue && @$queue >= $max;
Branch: 1 branch
BranchTrueFalseTotal
@$queue and @$queue >= $max and do { $self->_remove(shift(@$queue)->[1]) } 0 155 155
Condition66%2/3
@$queue and @$queue >= $max
!ll&&!rl&&r
14870
MC/DC0%0/2
@$queue and @$queue >= $max
@$queue @$queue >= $max
Truth table66%2/3
A and B
A= @$queueB= @$queue >= $max
ABresult
0X0
100
111
313 155 push @$queue, [join(':', $self->transactor->endpoint($tx)), $id];
314 }
315  
316 160 ▶sub _start {
Subroutine _start: called CC=11 SCAR=29.0
317 160 my ($self, $loop, $tx, $cb) = @_;
318  
319 # Application server
320 160 $self->emit(prepare => $tx);
321 160 my $url = $tx->req->url;
322 160 ▶ if (!$url->is_abs && (my $server = $self->server)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $url->is_abs and my $server = $self->server) 153 7 160
Condition66%2/3
not $url->is_abs and my $server = $self->server
!ll&&!rl&&r
70153
MC/DC50%1/2
not $url->is_abs and my $server = $self->server
not $url->is_abs my $server = $self->server
Truth table66%2/3
not(A) and B
A= not $url->is_absB= my $server = $self->server
ABresult
0X0
100
111
323 153 ▶ my $base = $loop == $self->ioloop ? $server->url : $server->nb_url;
Branch: 1 branch
BranchTrueFalseTotal
$loop == $self->ioloop ? : 153 0 153
324 153 $url->scheme($base->scheme)->host($base->host)->port($base->port);
325 }
326  
327 160 $_->prepare($tx) for $self->proxy, $self->cookie_jar;
328 160 my $max = $self->max_response_size;
329 160 ▶ $tx->res->max_message_size($max) if defined $max;
Branch: 1 branch
BranchTrueFalseTotal
if defined $max 0 160 160
330 160 $self->emit(start => $tx);
331  
332 # Allow test servers sharing the same event loop to clean up connections
333 160 ▶ !$loop->next_tick(sub { }) and $loop->one_tick unless $loop->is_running;
Subroutine __ANON__: called CC=1 SCAR=1.6
Branch: 1 branch
BranchTrueFalseTotal
unless $loop->is_running 160 0 160
Condition33%2/6
$loop->is_running || ($loop->next_tick(sub { } ) || $loop->one_tick)
l!l
01600
$loop->next_tick(sub { } ) or $loop->one_tick
l!l
01600
MC/DC0%0/3
$loop->is_running || ($loop->next_tick(sub { } ) || $loop->one_tick)
$loop->is_running $loop->next_tick(sub { } ) $loop->one_tick
Truth table0%0/4
A || B or C
A= $loop->is_runningB= $loop->next_tick(sub { } )C= $loop->one_tick
ABCresult
1XX1
01X1
0011
0000
334 160 ▶ return undef unless my $id = $self->_connection($loop, $tx, $cb);
Branch: 1 branch
BranchTrueFalseTotal
unless my $id = $self->_connection($loop, $tx, $cb) 0 160 160
335  
336 160 ▶ if (my $t = $self->request_timeout) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $t = $self->request_timeout) 0 160 160
337 0 weaken $self;
338 0 ▶ $self->{connections}{$id}{timeout} ||= $loop->timer($t => sub { $self->_error($id, 'Request timeout') });
Subroutine __ANON__: not called CC=1 SCAR=6.9
Condition0%0/3
$self->{"connections"}{$id}{"timeout"} ||= $loop->timer($t, sub { $self->_error($id, "Request timeout"); } )
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"connections"}{$id}{"timeout"} ||= $loop->timer($t, sub { $self->_error($id, "Request timeout"); } )
$self->{"connections"}{$id}{"timeout"} $loop->timer($t, sub { $self->_error($id, "Request timeout"); } )
Truth table0%0/3
A ||= B
A= $self->{"connections"}{$id}{"timeout"}B= $loop->timer($t, sub { $self->_error($id, "Request timeout"); } )
ABresult
1X1
011
000
339 }
340  
341 160 return $id;
342 }
343  
344 0 ▶sub _url { shift->req->url->to_abs }
Subroutine _url: not called CC=1 SCAR=6.9
345  
346 347 ▶sub _write {
Subroutine _write: called CC=4 SCAR=14.2
347 347 my ($self, $id) = @_;
348  
349 # Protect from resume event recursion
350 347 my $c = $self->{connections}{$id};
351 347 ▶ return if !(my $tx = $c->{tx}) || $c->{writing};
Branch: 1 branch
BranchTrueFalseTotal
if not my $tx = $c->{"tx"} or $c->{"writing"} 0 347 347
Condition33%1/3
not my $tx = $c->{"tx"} or $c->{"writing"}
l!l&&r!l&&!r
00347
MC/DC0%0/2
not my $tx = $c->{"tx"} or $c->{"writing"}
not my $tx = $c->{"tx"} $c->{"writing"}
Truth table33%1/3
not(A) or B
A= not my $tx = $c->{"tx"}B= $c->{"writing"}
ABresult
1X1
011
000
352 347 local $c->{writing} = 1;
353 347 my $chunk = $tx->client_write;
354 347 warn term_escape "-- Client >>> Server (@{[_url($tx)]})\n$chunk\n" if DEBUG;
355 347 ▶ return unless length $chunk;
Branch: 1 branch
BranchTrueFalseTotal
unless length $chunk 165 182 347
356  
357 182 weaken $self;
358 182 ▶ $c->{ioloop}->stream($id)->write($chunk => sub { $self && $self->_write($id) });
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
$self and $self->_write($id) 181 0 181
359 }
360  
361 23 1;
362  
363 =encoding utf8
364  
365 =head1 NAME
366  
367 Mojo::UserAgent - Non-blocking I/O HTTP and WebSocket user agent
368  
369 =head1 SYNOPSIS
370  
371 use Mojo::UserAgent;
372  
373 # Fine grained response handling (dies on connection errors)
374 my $ua = Mojo::UserAgent->new;
375 my $res = $ua->get('docs.mojolicious.org')->result;
376 if ($res->is_success) { say $res->body }
377 elsif ($res->is_error) { say $res->message }
378 elsif ($res->code == 301) { say $res->headers->location }
379 else { say 'Whatever...' }
380  
381 # Say hello to the Unicode snowman and include an Accept header
382 say $ua->get('www.☃.net?hello=there' => {Accept => '*/*'})->result->body;
383  
384 # Extract data from HTML and XML resources with CSS selectors
385 say $ua->get('www.perl.org')->result->dom->at('title')->text;
386  
387 # Scrape the latest headlines from a news site
388 say $ua->get('blogs.perl.org')->result->dom->find('h2 > a')->map('text')->join("\n");
389  
390 # IPv6 PUT request with Content-Type header and content
391 my $tx = $ua->put('[::1]:3000' => {'Content-Type' => 'text/plain'} => 'Hi!');
392  
393 # Quick JSON API request with Basic authentication
394 my $url = Mojo::URL->new('https://example.com/test.json')->userinfo('sri:☃');
395 my $value = $ua->get($url)->result->json;
396  
397 # JSON POST (application/json) with TLS certificate authentication
398 my $tx = $ua->cert('tls.crt')->key('tls.key')->post('https://example.com' => json => {top => 'secret'});
399  
400 # Form POST (application/x-www-form-urlencoded)
401 my $tx = $ua->post('https://metacpan.org/search' => form => {q => 'mojo'});
402  
403 # Search DuckDuckGo anonymously through Tor
404 $ua->proxy->http('socks://127.0.0.1:9050');
405 say $ua->get('api.3g2upl4pq6kufc4m.onion/?q=mojolicious&format=json')->result->json('/Abstract');
406  
407 # GET request via UNIX domain socket "/tmp/myapp.sock" (percent encoded slash)
408 say $ua->get('http+unix://%2Ftmp%2Fmyapp.sock/test')->result->body;
409  
410 # Follow redirects to download Mojolicious from GitHub
411 $ua->max_redirects(5)
412 ->get('https://www.github.com/mojolicious/mojo/tarball/main')
413 ->result->save_to('/home/sri/mojo.tar.gz');
414  
415 # Non-blocking request
416 $ua->get('mojolicious.org' => sub ($ua, $tx) { say $tx->result->dom->at('title')->text });
417 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
418  
419 # Concurrent non-blocking requests (synchronized with promises)
420 my $mojo_promise = $ua->get_p('mojolicious.org');
421 my $cpan_promise = $ua->get_p('cpan.org');
422 Mojo::Promise->all($mojo_promise, $cpan_promise)->then(sub ($mojo, $cpan) {
423 say $mojo->[0]->result->dom->at('title')->text;
424 say $cpan->[0]->result->dom->at('title')->text;
425 })->wait;
426  
427 # WebSocket connection sending and receiving JSON via UNIX domain socket
428 $ua->websocket('ws+unix://%2Ftmp%2Fmyapp.sock/echo.json' => sub ($ua, $tx) {
429 say 'WebSocket handshake failed!' and return unless $tx->is_websocket;
430 $tx->on(json => sub ($tx, $hash) {
431 say "WebSocket message via JSON: $hash->{msg}";
432 $tx->finish;
433 });
434 $tx->send({json => {msg => 'Hello World!'}});
435 });
436 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
437  
438 =head1 DESCRIPTION
439  
440 L<Mojo::UserAgent> is a full featured non-blocking I/O HTTP and WebSocket user agent, with IPv6, TLS, SNI, IDNA,
441 HTTP/SOCKS5 proxy, UNIX domain socket, Comet (long polling), Promises/A+, keep-alive, connection pooling, timeout,
442 cookie, multipart, gzip compression and multiple event loop support.
443  
444 All connections will be reset automatically if a new process has been forked, this allows multiple processes to share
445 the same L<Mojo::UserAgent> object safely.
446  
447 For better scalability (epoll, kqueue) and to provide non-blocking name resolution, SOCKS5 as well as TLS support, the
448 optional modules L<EV> (4.32+), L<Net::DNS::Native> (0.15+), L<IO::Socket::Socks> (0.64+) and L<IO::Socket::SSL>
449 (2.009+) will be used automatically if possible. Individual features can also be disabled with the C<MOJO_NO_NNR>,
450 C<MOJO_NO_SOCKS> and C<MOJO_NO_TLS> environment variables.
451  
452 See L<Mojolicious::Guides::Cookbook/"USER AGENT"> for more.
453  
454 =head1 EVENTS
455  
456 L<Mojo::UserAgent> inherits all events from L<Mojo::EventEmitter> and can emit the following new ones.
457  
458 =head2 prepare
459  
460 $ua->on(prepare => sub ($ua, $tx) {...});
461  
462 Emitted whenever a new transaction is being prepared, before relative URLs are rewritten and cookies added. This
463 includes automatically prepared proxy C<CONNECT> requests and followed redirects.
464  
465 $ua->on(prepare => sub ($ua, $tx) {
466 $tx->req->url(Mojo::URL->new('/mock-mojolicious')) if $tx->req->url->host eq 'mojolicious.org';
467 });
468  
469 =head2 start
470  
471 $ua->on(start => sub ($ua, $tx) {...});
472  
473 Emitted whenever a new transaction is about to start. This includes automatically prepared proxy C<CONNECT> requests
474 and followed redirects.
475  
476 $ua->on(start => sub ($ua, $tx) {
477 $tx->req->headers->header('X-Bender' => 'Bite my shiny metal ass!');
478 });
479  
480 =head1 ATTRIBUTES
481  
482 L<Mojo::UserAgent> implements the following attributes.
483  
484 =head2 ca
485  
486 my $ca = $ua->ca;
487 $ua = $ua->ca('/etc/tls/ca.crt');
488  
489 Path to TLS certificate authority file used to verify the peer certificate, defaults to the value of the
490 C<MOJO_CA_FILE> environment variable.
491  
492 # Show certificate authorities for debugging
493 IO::Socket::SSL::set_defaults(SSL_verify_callback => sub { say "Authority: $_[2]" and return $_[0] });
494  
495 =head2 cert
496  
497 my $cert = $ua->cert;
498 $ua = $ua->cert('/etc/tls/client.crt');
499  
500 Path to TLS certificate file, defaults to the value of the C<MOJO_CERT_FILE> environment variable.
501  
502 =head2 connect_timeout
503  
504 my $timeout = $ua->connect_timeout;
505 $ua = $ua->connect_timeout(5);
506  
507 Maximum amount of time in seconds establishing a connection may take before getting canceled, defaults to the value of
508 the C<MOJO_CONNECT_TIMEOUT> environment variable or C<10>.
509  
510 =head2 cookie_jar
511  
512 my $cookie_jar = $ua->cookie_jar;
513 $ua = $ua->cookie_jar(Mojo::UserAgent::CookieJar->new);
514  
515 Cookie jar to use for requests performed by this user agent, defaults to a L<Mojo::UserAgent::CookieJar> object.
516  
517 # Ignore all cookies
518 $ua->cookie_jar->ignore(sub { 1 });
519  
520 # Ignore cookies for public suffixes
521 my $ps = IO::Socket::SSL::PublicSuffix->default;
522 $ua->cookie_jar->ignore(sub ($cookie) {
523 return undef unless my $domain = $cookie->domain;
524 return ($ps->public_suffix($domain))[0] eq '';
525 });
526  
527 # Add custom cookie to the jar
528 $ua->cookie_jar->add(
529 Mojo::Cookie::Response->new(
530 name => 'foo',
531 value => 'bar',
532 domain => 'docs.mojolicious.org',
533 path => '/Mojolicious'
534 )
535 );
536  
537 =head2 inactivity_timeout
538  
539 my $timeout = $ua->inactivity_timeout;
540 $ua = $ua->inactivity_timeout(15);
541  
542 Maximum amount of time in seconds a connection can be inactive before getting closed, defaults to the value of the
543 C<MOJO_INACTIVITY_TIMEOUT> environment variable or C<40>. Setting the value to C<0> will allow connections to be
544 inactive indefinitely.
545  
546 =head2 insecure
547  
548 my $bool = $ua->insecure;
549 $ua = $ua->insecure($bool);
550  
551 Do not require a valid TLS certificate to access HTTPS/WSS sites, defaults to the value of the C<MOJO_INSECURE>
552 environment variable.
553  
554 # Disable TLS certificate verification for testing
555 say $ua->insecure(1)->get('https://127.0.0.1:3000')->result->code;
556  
557 =head2 ioloop
558  
559 my $loop = $ua->ioloop;
560 $ua = $ua->ioloop(Mojo::IOLoop->new);
561  
562 Event loop object to use for blocking I/O operations, defaults to a L<Mojo::IOLoop> object.
563  
564 =head2 key
565  
566 my $key = $ua->key;
567 $ua = $ua->key('/etc/tls/client.crt');
568  
569 Path to TLS key file, defaults to the value of the C<MOJO_KEY_FILE> environment variable.
570  
571 =head2 max_connections
572  
573 my $max = $ua->max_connections;
574 $ua = $ua->max_connections(5);
575  
576 Maximum number of keep-alive connections that the user agent will retain before it starts closing the oldest ones,
577 defaults to C<5>. Setting the value to C<0> will prevent any connections from being kept alive.
578  
579 =head2 max_redirects
580  
581 my $max = $ua->max_redirects;
582 $ua = $ua->max_redirects(3);
583  
584 Maximum number of redirects the user agent will follow before it fails, defaults to the value of the
585 C<MOJO_MAX_REDIRECTS> environment variable or C<0>.
586  
587 =head2 max_response_size
588  
589 my $max = $ua->max_response_size;
590 $ua = $ua->max_response_size(16777216);
591  
592 Maximum response size in bytes, defaults to the value of L<Mojo::Message::Response/"max_message_size">. Setting the
593 value to C<0> will allow responses of indefinite size. Note that increasing this value can also drastically increase
594 memory usage, should you for example attempt to parse an excessively large response body with the methods
595 L<Mojo::Message/"dom"> or L<Mojo::Message/"json">.
596  
597 =head2 proxy
598  
599 my $proxy = $ua->proxy;
600 $ua = $ua->proxy(Mojo::UserAgent::Proxy->new);
601  
602 Proxy manager, defaults to a L<Mojo::UserAgent::Proxy> object.
603  
604 # Detect proxy servers from environment
605 $ua->proxy->detect;
606  
607 # Manually configure HTTP proxy (using CONNECT for HTTPS/WebSockets)
608 $ua->proxy->http('http://127.0.0.1:8080')->https('http://127.0.0.1:8080');
609  
610 # Manually configure Tor (SOCKS5)
611 $ua->proxy->http('socks://127.0.0.1:9050')->https('socks://127.0.0.1:9050');
612  
613 # Manually configure UNIX domain socket (using CONNECT for HTTPS/WebSockets)
614 $ua->proxy->http('http+unix://%2Ftmp%2Fproxy.sock') ->https('http+unix://%2Ftmp%2Fproxy.sock');
615  
616 =head2 request_timeout
617  
618 my $timeout = $ua->request_timeout;
619 $ua = $ua->request_timeout(5);
620  
621 Maximum amount of time in seconds establishing a connection, sending the request and receiving a whole response may
622 take before getting canceled, defaults to the value of the C<MOJO_REQUEST_TIMEOUT> environment variable or C<0>.
623 Setting the value to C<0> will allow the user agent to wait indefinitely. The timeout will reset for every followed
624 redirect.
625  
626 # Total limit of 5 seconds, of which 3 seconds may be spent connecting
627 $ua->max_redirects(0)->connect_timeout(3)->request_timeout(5);
628  
629 =head2 server
630  
631 my $server = $ua->server;
632 $ua = $ua->server(Mojo::UserAgent::Server->new);
633  
634 Application server relative URLs will be processed with, defaults to a L<Mojo::UserAgent::Server> object.
635  
636 # Mock web service
637 $ua->server->app(Mojolicious->new);
638 $ua->server->app->get('/time' => sub ($c) {
639 $c->render(json => {now => time});
640 });
641 my $time = $ua->get('/time')->result->json->{now};
642  
643 # Change log level
644 $ua->server->app->log->level('fatal');
645  
646 # Port currently used for processing relative URLs blocking
647 say $ua->server->url->port;
648  
649 # Port currently used for processing relative URLs non-blocking
650 say $ua->server->nb_url->port;
651  
652 =head2 socket_options
653  
654 my $options = $ua->socket_options;
655 $ua = $ua->socket_options({LocalAddr => '127.0.0.1'});
656  
657 Additional options for L<IO::Socket::IP> when opening new connections.
658  
659 =head2 tls_options
660  
661 my $options = $ua->tls_options;
662 $ua = $ua->tls_options({SSL_cipher_list => 'DEFAULT:!DH@SECLEVEL=1'});
663  
664 Additional options for L<IO::Socket::SSL> when opening new connections.
665  
666 =head2 transactor
667  
668 my $t = $ua->transactor;
669 $ua = $ua->transactor(Mojo::UserAgent::Transactor->new);
670  
671 Transaction builder, defaults to a L<Mojo::UserAgent::Transactor> object.
672  
673 # Change name of user agent
674 $ua->transactor->name('MyUA 1.0');
675  
676 # Disable compression
677 $ua->transactor->compressed(0);
678  
679 =head1 METHODS
680  
681 L<Mojo::UserAgent> inherits all methods from L<Mojo::EventEmitter> and implements the following new ones.
682  
683 =head2 build_tx
684  
685 my $tx = $ua->build_tx(GET => 'example.com');
686 my $tx = $ua->build_tx(PUT => 'http://example.com' => {Accept => '*/*'} => 'Content!');
687 my $tx = $ua->build_tx(PUT => 'http://example.com' => {Accept => '*/*'} => form => {a => 'b'});
688 my $tx = $ua->build_tx(PUT => 'http://example.com' => {Accept => '*/*'} => json => {a => 'b'});
689  
690 Generate L<Mojo::Transaction::HTTP> object with L<Mojo::UserAgent::Transactor/"tx">.
691  
692 # Request with custom cookie
693 my $tx = $ua->build_tx(GET => 'https://example.com/account');
694 $tx->req->cookies({name => 'user', value => 'sri'});
695 $tx = $ua->start($tx);
696  
697 # Deactivate gzip compression
698 my $tx = $ua->build_tx(GET => 'example.com');
699 $tx->req->headers->remove('Accept-Encoding');
700 $tx = $ua->start($tx);
701  
702 # Interrupt response by raising an error
703 my $tx = $ua->build_tx(GET => 'http://example.com');
704 $tx->res->on(progress => sub ($res) {
705 return unless my $server = $res->headers->server;
706 $res->error({message => 'Oh noes, it is IIS!'}) if $server =~ /IIS/;
707 });
708 $tx = $ua->start($tx);
709  
710 =head2 build_websocket_tx
711  
712 my $tx = $ua->build_websocket_tx('ws://example.com');
713 my $tx = $ua->build_websocket_tx( 'ws://example.com' => {DNT => 1} => ['v1.proto']);
714  
715 Generate L<Mojo::Transaction::HTTP> object with L<Mojo::UserAgent::Transactor/"websocket">.
716  
717 # Custom WebSocket handshake with cookie
718 my $tx = $ua->build_websocket_tx('wss://example.com/echo');
719 $tx->req->cookies({name => 'user', value => 'sri'});
720 $ua->start($tx => sub ($ua, $tx) {
721 say 'WebSocket handshake failed!' and return unless $tx->is_websocket;
722 $tx->on(message => sub ($tx, $msg) {
723 say "WebSocket message: $msg";
724 $tx->finish;
725 });
726 $tx->send('Hi!');
727 });
728 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
729  
730 =head2 delete
731  
732 my $tx = $ua->delete('example.com');
733 my $tx = $ua->delete('http://example.com' => {Accept => '*/*'} => 'Content!');
734 my $tx = $ua->delete('http://example.com' => {Accept => '*/*'} => form => {a => 'b'});
735 my $tx = $ua->delete('http://example.com' => {Accept => '*/*'} => json => {a => 'b'});
736  
737 Perform blocking C<DELETE> request and return resulting L<Mojo::Transaction::HTTP> object, takes the same arguments as
738 L<Mojo::UserAgent::Transactor/"tx"> (except for the C<DELETE> method, which is implied). You can also append a callback
739 to perform requests non-blocking.
740  
741 $ua->delete('http://example.com' => json => {a => 'b'} => sub ($ua, $tx) { say $tx->result->body });
742 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
743  
744 =head2 delete_p
745  
746 my $promise = $ua->delete_p('http://example.com');
747  
748 Same as L</"delete">, but performs all requests non-blocking and returns a L<Mojo::Promise> object instead of accepting
749 a callback.
750  
751 $ua->delete_p('http://example.com' => json => {a => 'b'})->then(sub ($tx) {
752 say $tx->result->body;
753 })->catch(sub ($err) {
754 warn "Connection error: $err";
755 })->wait;
756  
757 =head2 get
758  
759 my $tx = $ua->get('example.com');
760 my $tx = $ua->get('http://example.com' => {Accept => '*/*'} => 'Content!');
761 my $tx = $ua->get('http://example.com' => {Accept => '*/*'} => form => {a => 'b'});
762 my $tx = $ua->get('http://example.com' => {Accept => '*/*'} => json => {a => 'b'});
763  
764 Perform blocking C<GET> request and return resulting L<Mojo::Transaction::HTTP> object, takes the same arguments as
765 L<Mojo::UserAgent::Transactor/"tx"> (except for the C<GET> method, which is implied). You can also append a callback to
766 perform requests non-blocking.
767  
768 $ua->get('http://example.com' => json => {a => 'b'} => sub ($ua, $tx) { say $tx->result->body });
769 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
770  
771 =head2 get_p
772  
773 my $promise = $ua->get_p('http://example.com');
774  
775 Same as L</"get">, but performs all requests non-blocking and returns a L<Mojo::Promise> object instead of accepting a
776 callback.
777  
778 $ua->get_p('http://example.com' => json => {a => 'b'})->then(sub ($tx) {
779 say $tx->result->body;
780 })->catch(sub ($err) {
781 warn "Connection error: $err";
782 })->wait;
783  
784 =head2 head
785  
786 my $tx = $ua->head('example.com');
787 my $tx = $ua->head('http://example.com' => {Accept => '*/*'} => 'Content!');
788 my $tx = $ua->head('http://example.com' => {Accept => '*/*'} => form => {a => 'b'});
789 my $tx = $ua->head('http://example.com' => {Accept => '*/*'} => json => {a => 'b'});
790  
791 Perform blocking C<HEAD> request and return resulting L<Mojo::Transaction::HTTP> object, takes the same arguments as
792 L<Mojo::UserAgent::Transactor/"tx"> (except for the C<HEAD> method, which is implied). You can also append a callback
793 to perform requests non-blocking.
794  
795 $ua->head('http://example.com' => json => {a => 'b'} => sub ($ua, $tx) { say $tx->result->body });
796 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
797  
798 =head2 head_p
799  
800 my $promise = $ua->head_p('http://example.com');
801  
802 Same as L</"head">, but performs all requests non-blocking and returns a L<Mojo::Promise> object instead of accepting a
803 callback.
804  
805 $ua->head_p('http://example.com' => json => {a => 'b'})->then(sub ($tx) {
806 say $tx->result->body;
807 })->catch(sub ($err) {
808 warn "Connection error: $err";
809 })->wait;
810  
811 =head2 options
812  
813 my $tx = $ua->options('example.com');
814 my $tx = $ua->options('http://example.com' => {Accept => '*/*'} => 'Content!');
815 my $tx = $ua->options('http://example.com' => {Accept => '*/*'} => form => {a => 'b'});
816 my $tx = $ua->options('http://example.com' => {Accept => '*/*'} => json => {a => 'b'});
817  
818 Perform blocking C<OPTIONS> request and return resulting L<Mojo::Transaction::HTTP> object, takes the same arguments as
819 L<Mojo::UserAgent::Transactor/"tx"> (except for the C<OPTIONS> method, which is implied). You can also append a
820 callback to perform requests non-blocking.
821  
822 $ua->options('http://example.com' => json => {a => 'b'} => sub ($ua, $tx) { say $tx->result->body });
823 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
824  
825 =head2 options_p
826  
827 my $promise = $ua->options_p('http://example.com');
828  
829 Same as L</"options">, but performs all requests non-blocking and returns a L<Mojo::Promise> object instead of
830 accepting a callback.
831  
832 $ua->options_p('http://example.com' => json => {a => 'b'})->then(sub ($tx) {
833 say $tx->result->body;
834 })->catch(sub ($err) {
835 warn "Connection error: $err";
836 })->wait;
837  
838 =head2 patch
839  
840 my $tx = $ua->patch('example.com');
841 my $tx = $ua->patch('http://example.com' => {Accept => '*/*'} => 'Content!');
842 my $tx = $ua->patch('http://example.com' => {Accept => '*/*'} => form => {a => 'b'});
843 my $tx = $ua->patch('http://example.com' => {Accept => '*/*'} => json => {a => 'b'});
844  
845 Perform blocking C<PATCH> request and return resulting L<Mojo::Transaction::HTTP> object, takes the same arguments as
846 L<Mojo::UserAgent::Transactor/"tx"> (except for the C<PATCH> method, which is implied). You can also append a callback
847 to perform requests non-blocking.
848  
849 $ua->patch('http://example.com' => json => {a => 'b'} => sub ($ua, $tx) { say $tx->result->body });
850 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
851  
852 =head2 patch_p
853  
854 my $promise = $ua->patch_p('http://example.com');
855  
856 Same as L</"patch">, but performs all requests non-blocking and returns a L<Mojo::Promise> object instead of accepting
857 a callback.
858  
859 $ua->patch_p('http://example.com' => json => {a => 'b'})->then(sub ($tx) {
860 say $tx->result->body;
861 })->catch(sub ($err) {
862 warn "Connection error: $err";
863 })->wait;
864  
865 =head2 post
866  
867 my $tx = $ua->post('example.com');
868 my $tx = $ua->post('http://example.com' => {Accept => '*/*'} => 'Content!');
869 my $tx = $ua->post('http://example.com' => {Accept => '*/*'} => form => {a => 'b'});
870 my $tx = $ua->post('http://example.com' => {Accept => '*/*'} => json => {a => 'b'});
871  
872 Perform blocking C<POST> request and return resulting L<Mojo::Transaction::HTTP> object, takes the same arguments as
873 L<Mojo::UserAgent::Transactor/"tx"> (except for the C<POST> method, which is implied). You can also append a callback
874 to perform requests non-blocking.
875  
876 $ua->post('http://example.com' => json => {a => 'b'} => sub ($ua, $tx) { say $tx->result->body });
877 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
878  
879 =head2 post_p
880  
881 my $promise = $ua->post_p('http://example.com');
882  
883 Same as L</"post">, but performs all requests non-blocking and returns a L<Mojo::Promise> object instead of accepting a
884 callback.
885  
886 $ua->post_p('http://example.com' => json => {a => 'b'})->then(sub ($tx) {
887 say $tx->result->body;
888 })->catch(sub ($err) {
889 warn "Connection error: $err";
890 })->wait;
891  
892 =head2 put
893  
894 my $tx = $ua->put('example.com');
895 my $tx = $ua->put('http://example.com' => {Accept => '*/*'} => 'Content!');
896 my $tx = $ua->put('http://example.com' => {Accept => '*/*'} => form => {a => 'b'});
897 my $tx = $ua->put('http://example.com' => {Accept => '*/*'} => json => {a => 'b'});
898  
899 Perform blocking C<PUT> request and return resulting L<Mojo::Transaction::HTTP> object, takes the same arguments as
900 L<Mojo::UserAgent::Transactor/"tx"> (except for the C<PUT> method, which is implied). You can also append a callback to
901 perform requests non-blocking.
902  
903 $ua->put('http://example.com' => json => {a => 'b'} => sub ($ua, $tx) { say $tx->result->body });
904 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
905  
906 =head2 put_p
907  
908 my $promise = $ua->put_p('http://example.com');
909  
910 Same as L</"put">, but performs all requests non-blocking and returns a L<Mojo::Promise> object instead of accepting a
911 callback.
912  
913 $ua->put_p('http://example.com' => json => {a => 'b'})->then(sub ($tx) {
914 say $tx->result->body;
915 })->catch(sub ($err) {
916 warn "Connection error: $err";
917 })->wait;
918  
919 =head2 query
920  
921 my $tx = $ua->query('example.com');
922 my $tx = $ua->query('http://example.com' => {Accept => '*/*'} => 'Content!');
923 my $tx = $ua->query('http://example.com' => {Accept => '*/*'} => form => {a => 'b'});
924 my $tx = $ua->query('http://example.com' => {Accept => '*/*'} => json => {a => 'b'});
925  
926 Perform blocking C<QUERY> request and return resulting L<Mojo::Transaction::HTTP> object, takes the same arguments as
927 L<Mojo::UserAgent::Transactor/"tx"> (except for the C<QUERY> method, which is implied). You can also append a callback
928 to perform requests non-blocking.
929  
930 $ua->query('http://example.com' => json => {a => 'b'} => sub ($ua, $tx) { say $tx->result->body });
931 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
932  
933 =head2 query_p
934  
935 my $promise = $ua->query_p('http://example.com');
936  
937 Same as L</"query">, but performs all requests non-blocking and returns a L<Mojo::Promise> object instead of accepting
938 a callback.
939  
940 $ua->query_p('http://example.com' => json => {a => 'b'})->then(sub ($tx) {
941 say $tx->result->body;
942 })->catch(sub ($err) {
943 warn "Connection error: $err";
944 })->wait;
945  
946 =head2 start
947  
948 my $tx = $ua->start(Mojo::Transaction::HTTP->new);
949  
950 Perform blocking request for a custom L<Mojo::Transaction::HTTP> object, which can be prepared manually or with
951 L</"build_tx">. You can also append a callback to perform requests non-blocking.
952  
953 my $tx = $ua->build_tx(GET => 'http://example.com');
954 $ua->start($tx => sub ($ua, $tx) { say $tx->result->body });
955 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
956  
957 =head2 start_p
958  
959 my $promise = $ua->start_p(Mojo::Transaction::HTTP->new);
960  
961 Same as L</"start">, but performs all requests non-blocking and returns a L<Mojo::Promise> object instead of accepting
962 a callback.
963  
964 my $tx = $ua->build_tx(GET => 'http://example.com');
965 $ua->start_p($tx)->then(sub ($tx) {
966 say $tx->result->body;
967 })->catch(sub ($err) {
968 warn "Connection error: $err";
969 })->wait;
970  
971 =head2 websocket
972  
973 $ua->websocket('ws://example.com' => sub {...});
974 $ua->websocket('ws://example.com' => {DNT => 1} => ['v1.proto'] => sub {...});
975  
976 Open a non-blocking WebSocket connection with transparent handshake, takes the same arguments as
977 L<Mojo::UserAgent::Transactor/"websocket">. The callback will receive either a L<Mojo::Transaction::WebSocket> or
978 L<Mojo::Transaction::HTTP> object, depending on if the handshake was successful.
979  
980 $ua->websocket('wss://example.com/echo' => ['v1.proto'] => sub ($ua, $tx) {
981 say 'WebSocket handshake failed!' and return unless $tx->is_websocket;
982 say 'Subprotocol negotiation failed!' and return unless $tx->protocol;
983 $tx->on(finish => sub ($tx, $code, $reason) { say "WebSocket closed with status $code." });
984 $tx->on(message => sub ($tx, $msg) {
985 say "WebSocket message: $msg";
986 $tx->finish;
987 });
988 $tx->send('Hi!');
989 });
990 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
991  
992 You can activate C<permessage-deflate> compression by setting the C<Sec-WebSocket-Extensions> header, this can result
993 in much better performance, but also increases memory usage by up to 300KiB per connection.
994  
995 $ua->websocket('ws://example.com/foo' => {
996 'Sec-WebSocket-Extensions' => 'permessage-deflate'
997 } => sub {...});
998  
999 =head2 websocket_p
1000  
1001 my $promise = $ua->websocket_p('ws://example.com');
1002  
1003 Same as L</"websocket">, but returns a L<Mojo::Promise> object instead of accepting a callback.
1004  
1005 $ua->websocket_p('wss://example.com/echo')->then(sub ($tx) {
1006 my $promise = Mojo::Promise->new;
1007 $tx->on(finish => sub { $promise->resolve });
1008 $tx->on(message => sub ($tx, $msg) {
1009 say "WebSocket message: $msg";
1010 $tx->finish;
1011 });
1012 $tx->send('Hi!');
1013 return $promise;
1014 })->catch(sub ($err) {
1015 warn "WebSocket error: $err";
1016 })->wait;
1017  
1018 =head1 DEBUGGING
1019  
1020 You can set the C<MOJO_CLIENT_DEBUG> environment variable to get some advanced diagnostics information printed to
1021 C<STDERR>.
1022  
1023 MOJO_CLIENT_DEBUG=1
1024  
1025 =head1 SEE ALSO
1026  
1027 L<Mojolicious>, L<Mojolicious::Guides>, L<https://mojolicious.org>.
1028  
1029 =cut
« Mojo/Util.pm ↑ Summary Mojo/IOLoop/Client.pm »