blib/lib/PAGI/App/Healthcheck.pm untested

filter: Statementstmt 0.0% 0 / 49 Branchbran 0.0% 0 / 14 Conditioncond 0.0% 0 / 2 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 6 Podpod 0.0% 0 / 2 totaltotal 0.0% 0 / 73 CC 8 SCAR 38.1
CC
8
Cov
0%
to_app
72.0
new
2.0
BEGIN
2.0
CRAP 45.1
1 package PAGI::App::Healthcheck;
2 $PAGI::App::Healthcheck::VERSION = '0.002000';
3 use strict;
4 use warnings;
5 use Future::AsyncAwait;
6 use JSON::MaybeXS ();
7  
8 =head1 NAME
9  
10 PAGI::App::Healthcheck - Health check endpoint app
11  
12 =head1 SYNOPSIS
13  
14 use PAGI::App::Healthcheck;
15  
16 my $app = PAGI::App::Healthcheck->new(
17 checks => {
18 database => sub { check_db() },
19 },
20 )->to_app;
21  
22 =cut
23  
24 our $START_TIME = time();
25  
26 sub new {
27 my ($class, %args) = @_;
28  
29 return bless {
30 checks => $args{checks} // {},
31 version => $args{version},
32 }, $class;
33 }
34  
35 sub to_app {
36 my ($self) = @_;
37  
38 my $checks = $self->{checks};
39 my $version = $self->{version};
40  
41 return async sub {
42 my ($scope, $receive, $send) = @_;
43 my $all_ok = 1;
44 my %results;
45  
46 for my $name (sort keys %$checks) {
47 my $check = $checks->{$name};
48 my $result = { status => 'ok' };
49  
50 eval { my $ok = $check->(); $result->{status} = 'error' unless $ok; };
51 if ($@) {
52 $result->{status} = 'error';
53 $result->{message} = "$@";
54 $result->{message} =~ s/\s+$//;
55 }
56  
57 $results{$name} = $result;
58 $all_ok = 0 if $result->{status} eq 'error';
59 }
60  
61 my $response = {
62 status => $all_ok ? 'ok' : 'error',
63 timestamp => time(),
64 uptime => time() - $START_TIME,
65 };
66 $response->{version} = $version if defined $version;
67 $response->{checks} = \%results if %results;
68  
69 my $body = JSON::MaybeXS::encode_json($response);
70 my $status = $all_ok ? 200 : 503;
71  
72 await $send->({
73 type => 'http.response.start',
74 status => $status,
75 headers => [
76 ['content-type', 'application/json'],
77 ['content-length', length($body)],
78 ['cache-control', 'no-cache'],
79 ],
80 });
81 await $send->({ type => 'http.response.body', body => $body, more => 0 });
82 };
83 }
84  
85 1;
86  
87 __END__