File Coverage

examples/06-lifespan-state/app.pl
Criterion Covered Total %
statement 33 34 97.0
branch 8 12 66.6
condition 3 6 50.0
subroutine 6 6 100.0
pod n/a
total 50 58 86.2


line stmt bran cond sub pod time code
1 1     1   219727 use strict;
  1         2  
  1         38  
2 1     1   3 use warnings;
  1         1  
  1         41  
3 1     1   4 use Future::AsyncAwait;
  1         1  
  1         11  
4              
5 1     1   2 async sub handle_lifespan {
6 1         2 my ($scope, $receive, $send) = @_;
7              
8 1   50     2 my $state = $scope->{state} //= {};
9              
10 1         2 while (1) {
11 2         31 my $event = await $receive->();
12 2 100       149 if ($event->{type} eq 'lifespan.startup') {
    50          
13 1         2 $state->{greeting} = 'Hello from lifespan';
14 1         3 await $send->({ type => 'lifespan.startup.complete' });
15             }
16             elsif ($event->{type} eq 'lifespan.shutdown') {
17 1         6 await $send->({ type => 'lifespan.shutdown.complete' });
18 1         38 last;
19             }
20             }
21             }
22              
23 1     1   2 async sub handle_http {
24 1         3 my ($scope, $receive, $send) = @_;
25              
26 1   50     2 my $state = $scope->{state} // {};
27 1   50     3 my $greeting = $state->{greeting} // 'Hello';
28              
29             # Drain the request body (if any)
30 1         2 while (1) {
31 1         3 my $event = await $receive->();
32 1 50       21 last if $event->{type} ne 'http.request';
33 1 50       4 last unless $event->{more};
34             }
35              
36             await $send->({
37             type => 'http.response.start',
38             status => 200,
39             headers => [ [ 'content-type', 'text/plain' ] ],
40 1         7 });
41              
42 1         40 await $send->({ type => 'http.response.body', body => "$greeting via shared state", more => 0 });
43             }
44              
45 2     2   2 async sub app {
46 2         5 my ($scope, $receive, $send) = @_;
47              
48 2 100       7 return await handle_lifespan($scope, $receive, $send) if $scope->{type} eq 'lifespan';
49 1 50       5 return await handle_http($scope, $receive, $send) if $scope->{type} eq 'http';
50 0           die "Unsupported scope type: $scope->{type}";
51             }
52              
53             \&app;