AsyncAwait/Backend/Coro.pm

filter: Statementstmt 97.8% 93 / 95 Branchbran 85.7% 24 / 28 Conditioncond 33.3% 1 / 3 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 95.0% 19 / 20 Podpod 100% 2 / 2 totaltotal 92.6% 139 / 150 CC 17 SCAR 11.0
CC
17
Cov
94%
_parse_opts
5.2
await
5.0
async
5.0
CRAP 3.0
↑ Summary AsyncAwait.pm »
1 package Mojo::AsyncAwait::Backend::Coro;
2 9 ▶use Mojo::Base -strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3  
4 9 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
5 9 ▶use Coro::State ();
Subroutine BEGIN: called CC=1 SCAR=0.0
6 9 ▶use Mojo::Util;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 9 ▶use Mojo::Promise;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 9 ▶use Sub::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 9 ▶use Exporter 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 9 our @EXPORT = (qw/async await/);
13  
14 9 my $main = Coro::State->new;
15 9 $main->{desc} = 'Mojo::AsyncAwait::Backend::Coro/$main';
16  
17 # LIFO stack of coroutines waiting to come back to
18 # always has $main as the bottom of the stack
19 9 my @stack = ($main);
20  
21 # Coroutines that are ostensible done but need someone to kill them
22 9 my @clean;
23  
24 # _push adds a coroutine to the stack and enters it
25 # when control returns to the original pusher, it will clean up
26 # any coroutines that are waiting to be cleaned up
27  
28 22 ▶sub _push {
Subroutine _push: called CC=2 SCAR=6.9
29 22 push @stack, @_;
30 22 $stack[-2]->transfer($stack[-1]);
31 22 $_->cancel for @clean;
32 22 @clean = ();
33 }
34  
35 # _pop pops the current coroutine off the stack. If given a callback, it calls
36 # a callback on it, otherwise, schedules it for cleanup. It then transfers to
37 # the next one on the stack. Note that it can't pop-and-return (which would
38 # make more sense) because any action on it must happen before control is
39 # transfered away from it
40  
41 22 ▶sub _pop (;&) {
Subroutine _pop: called CC=3 SCAR=11.0
42 22 ▶ Carp::croak "Cannot leave the main thread"
Branch: 1 branch
BranchTrueFalseTotal
if $stack[-1] == $main 0 22 22
43 if $stack[-1] == $main;
44 22 my ($cb) = @_;
45 22 my $current = pop @stack;
46 22 ▶ if ($cb) { $cb->($current) }
Branch: 1 branch
BranchTrueFalseTotal
if ($cb) { } 11 11 22
47 11 else { push @clean, $current }
48 22 $current->transfer($stack[-1]);
49 }
50  
51 11 ▶sub async {
Subroutine async: called CC=5 SCAR=16.1
Pod documented
52 11 my $body = pop;
53 11 my $opts = _parse_opts(@_);
54 11 my @caller = caller;
55  
56 11 my $subname = "$caller[0]::__ASYNCSUB__";
57 11 my $bodyname = "$caller[0]::__ASYNCBODY__";
58 11 ▶ if (defined(my $name = $opts->{-name})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $name = $opts->{"-name"})) 3 8 11
59 3 ▶ $subname = $opts->{-install} ? "$caller[0]::$name" : "$subname($name)";
Branch: 1 branch
BranchTrueFalseTotal
$opts->{'-install'} ? : 2 1 3
60 3 $bodyname .= "($name)";
61 }
62 11 my $desc = "declared at $caller[1] line $caller[2]";
63  
64 11 ▶ Sub::Util::set_subname($bodyname => $body)
Branch: 1 branch
BranchTrueFalseTotal
if Sub::Util::subname($body) =~ /::__ANON__$/u 11 0 11
65 if Sub::Util::subname($body) =~ /::__ANON__$/;
66  
67 10 ▶ my $wrapped = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine doit: called CC=1 SCAR=0.0
68 10 my @caller = caller;
69 10 my $promise = Mojo::Promise->new;
70 11 ▶ my $coro = Coro::State->new(sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
71 11 ▶ eval {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { BEGIN { $^H{'Mojo::AsyncAwait::Backend::Coro/async'} = '1'; } $promise->resolve(&$body(@_)); 1 } } or $promise->reject($@) 10 1 11
72 9 ▶ BEGIN { $^H{'Mojo::AsyncAwait::Backend::Coro/async'} = 1 }
Subroutine BEGIN: called CC=1 SCAR=0.0
73 11 $promise->resolve($body->(@_)); 1
74 } or $promise->reject($@);
75 11 _pop;
76 10 }, @_);
77 10 $coro->{desc} = "$subname called at $caller[1] line $caller[2], $desc";
78 10 _push $coro;
79 10 return $promise;
80 11 };
81  
82 11 ▶ if ($opts->{-install}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts->{"-install"}) 2 9 11
83 2 Mojo::Util::monkey_patch $caller[0], $opts->{-name} => $wrapped;
84 2 return;
85 }
86  
87 9 Sub::Util::set_subname $subname => $wrapped;
88 9 return $wrapped;
89 }
90  
91 # this prototype prevents the perl tokenizer from seeing await as an
92 # indirect method
93  
94 13 ▶sub await (*) {
Subroutine await: called CC=5 SCAR=16.2
Pod documented
95 {
96 # check that our caller is actually an async function
97 9 ▶ no warnings 'uninitialized';
Subroutine BEGIN: called CC=1 SCAR=0.0
98 13 my $level = 1;
99 13 my ($caller, $hints) = (caller($level))[3, 10];
100  
101 # being inside of an eval is ok too
102 13 ▶ ($caller, $hints) = (caller(++$level))[3, 10] while $caller eq '(eval)';
Branch: 1 branch
BranchTrueFalseTotal
$caller eq "(eval)" and do { () = (caller ++$level)[3, 10] } 2 13 15
103  
104 Carp::croak 'await may only be called from in async function'
105 13 ▶ unless $hints->{'Mojo::AsyncAwait::Backend::Coro/async'};
Branch: 1 branch
BranchTrueFalseTotal
unless $hints->{"Mojo::AsyncAwait::Backend::Coro/async"} 2 11 13
106 }
107  
108 11 my $promise = Mojo::Promise->resolve($_[0]);
109  
110 11 my (@retvals, $err);
111 11 ▶ _pop {
Subroutine __ANON__: called CC=1 SCAR=0.4
112 11 my $current = shift;
113 $promise->then(
114 11 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
115 11 @retvals = @_;
116 11 _push $current;
117 },
118 0 ▶ sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
119 0 $err = shift;
120 0 _push $current;
121 }
122 11 );
123 11 };
124  
125 # "_push $current" in the above callback brings us here
126 11 ▶ Carp::croak($err) if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 11 11
127 11 ▶ return wantarray ? @retvals : $retvals[0];
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 1 10 11
128 }
129  
130 11 ▶sub _parse_opts {
Subroutine _parse_opts: called CC=5 SCAR=16.6
131 11 ▶ return {} unless @_;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ 8 3 11
132 return {
133 3 ▶ -name => shift,
Branch: 1 branch
BranchTrueFalseTotal
if @_ == 1 2 1 3
134 -install => 1,
135 } if @_ == 1;
136  
137 1 my %opts = @_;
138 Carp::croak 'Cannot install a sub without a name'
139 1 ▶ if $opts{-install} && !defined $opts{-name};
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"-install"} and not defined $opts{"-name"} 0 1 1
Condition33%1/3
$opts{"-install"} and not defined $opts{"-name"}
!ll&&!rl&&r
100
MC/DC0%0/2
$opts{"-install"} and not defined $opts{"-name"}
$opts{"-install"} not defined $opts{"-name"}
Truth table33%1/3
A and not(B)
A= $opts{"-install"}B= not defined $opts{"-name"}
ABresult
0X0
100
111
140  
141 1 return \%opts;
142 }
143  
144 9 1;
145  
146 =encoding utf8
147  
148 =head1 NAME
149  
150 Mojo::AsyncAwait::Backend::Coro - An Async/Await implementation for Mojolicious using Coro
151  
152 =head1 SYNOPSIS
153  
154 use Mojolicious::Lite -signatures;
155 use Mojo::AsyncAwait;
156  
157 get '/' => async sub ($c) {
158  
159 my $mojo = await $c->ua->get_p('https://mojolicious.org');
160 my $cpan = await $c->ua->get_p('https://metacpan.org');
161  
162 $c->render(json => {
163 mojo => $mojo->result->code,
164 cpan => $cpan->result->code
165 });
166 };
167  
168 app->start;
169  
170 =head1 DESCRIPTION
171  
172 As the name suggests, L<Mojo::AsyncAwait::Backend::Coro> is an implementation
173 of the Async/Await pattern, using L<Mojo::Promise> and L<Coro>. See more at
174 L<Mojo::AsyncAwait>.
175  
176 =head1 CAVEATS
177  
178 This implementation relies on L<Coro> which does some very magical things to
179 the Perl interpreter. All caveats that apply to using L<Coro::State> apply to
180 this module as well.
181  
182 Also note that while a L<Coro>-based implementation need not rely on L</await>
183 being called directly from an L</async> function, it is currently prohibitied
184 because it is likely that other/future implementations will rely on that
185 behavior and thus it should not be relied upon.
186  
187 =head1 KEYWORDS
188  
189 L<Mojo::AsyncAwait::Backend::Coro> provides two keywords (i.e. functions), both
190 exported by default. They are re-exported by L<Mojo::AsyncAwait> if it is the
191 chosen implementation.
192  
193 =head2 async
194  
195 my $sub = async sub { ... };
196  
197 The async keyword wraps a subroutine as an asynchronous subroutine which is
198 able to be suspended via L</await>. The return value(s) of the subroutine, when
199 called, will be wrapped in a L<Mojo::Promise>.
200  
201 The async keyword must be called with a subroutine reference, which will be the
202 body of the async subroutine.
203  
204 Note that the returned subroutine reference is not invoked for you.
205 If you want to immediately invoke it, you need to so manually.
206  
207 my $promise = async(sub{ ... })->();
208  
209 If called with a preceding name, the subroutine will be installed into the current package with that name.
210  
211 async installed_sub => sub { ... };
212 installed_sub();
213  
214 If called with key-value arguments starting with a dash, the following options are available.
215  
216 =over
217  
218 =item -install
219  
220 If set to a true value, the subroutine will be installed into the current package.
221 Default is false.
222 Setting this value to true without a C<-name> is an error.
223  
224 =item -name
225  
226 If C<-install> is false, this is a diagnostic name to be included in the subname for debugging purposes.
227 This name is seen in diagnostic information, like stack traces.
228  
229 my $named_sub = async -name => my_name => sub { ... };
230 $named_sub->();
231  
232 Otherwise this is the name that will be installed into the current package.
233  
234 =back
235  
236 Therefore, passing a bare name as is identical to setting both C<-name> and C<< -install => 1 >>.
237  
238 async -name => installed_sub, -install => 1 => sub { ... };
239 installed_sub();
240  
241 If the subroutine is installed, whether by passing a bare name or the C<-install> option, nothing is returned.
242 Otherwise the return value is the wrapped async subroutine reference.
243  
244 =head2 await
245  
246 my $tx = await Mojo::UserAgent->new->get_p('https://mojolicious.org');
247 my @results = await (async sub { ...; return @async_results })->();
248  
249 The await keyword suspends execution of an async sub until a promise is
250 fulfilled, returning the promise's results. In list context all promise results
251 are returned. For ease of use, in scalar context the first promise result is
252 returned and the remainder are discarded.
253  
254 If the value passed to await is not a promise (defined as having a C<then>
255 method), it will be wrapped in a Mojo::Promise for consistency. This is mostly
256 inconsequential to the user.
257  
258 Note that await can only take one promise as an argument. If you wanted to
259 await multiple promises you probably want L<Mojo::Promise/all> or less likely
260 L<Mojo::Promise/race>.
261  
262 my $results = await Mojo::Promise->all(@promises);
263  
264 =head1 SEE ALSO
265  
266 L<Mojo::Promise>, L<Mojo::IOLoop>, L<Coro>, L<Coro::State>
267  
268 =cut
↑ Summary AsyncAwait.pm »