| 1 | package PAGI::Middleware::Runtime; | ||
| 2 | $PAGI::Middleware::Runtime::VERSION = '0.002001'; | ||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | use parent 'PAGI::Middleware'; | ||
| 6 | use Future::AsyncAwait; | ||
| 7 | use Time::HiRes qw(time); | ||
| 8 | |||
| 9 | =head1 NAME | ||
| 10 | |||
| 11 | PAGI::Middleware::Runtime - Request timing middleware | ||
| 12 | |||
| 13 | =head1 SYNOPSIS | ||
| 14 | |||
| 15 | use PAGI::Middleware::Builder; | ||
| 16 | |||
| 17 | my $app = builder { | ||
| 18 | enable 'Runtime', | ||
| 19 | header => 'X-Runtime', | ||
| 20 | precision => 6; | ||
| 21 | $my_app; | ||
| 22 | }; | ||
| 23 | |||
| 24 | =head1 DESCRIPTION | ||
| 25 | |||
| 26 | PAGI::Middleware::Runtime measures the time taken to process a request | ||
| 27 | and adds it as a response header. This is useful for performance | ||
| 28 | monitoring and debugging. | ||
| 29 | |||
| 30 | =head1 CONFIGURATION | ||
| 31 | |||
| 32 | =over 4 | ||
| 33 | |||
| 34 | =item * header (default: 'X-Runtime') | ||
| 35 | |||
| 36 | The header name to use for the runtime value. | ||
| 37 | |||
| 38 | =item * precision (default: 6) | ||
| 39 | |||
| 40 | Number of decimal places for the duration in seconds. | ||
| 41 | |||
| 42 | =back | ||
| 43 | |||
| 44 | =cut | ||
| 45 | |||
| 46 | sub _init { | ||
| 47 | my ($self, $config) = @_; | ||
| 48 | |||
| 49 | $self->{header} = $config->{header} // 'X-Runtime'; | ||
| 50 | $self->{precision} = $config->{precision} // 6; | ||
| 51 | } | ||
| 52 | |||
| 53 | sub wrap { | ||
| 54 | my ($self, $app) = @_; | ||
| 55 | |||
| 56 | return async sub { | ||
| 57 | my ($scope, $receive, $send) = @_; | ||
| 58 | # Only handle HTTP requests | ||
| 59 | if ($scope->{type} ne 'http') { | ||
| 60 | await $app->($scope, $receive, $send); | ||
| 61 | return; | ||
| 62 | } | ||
| 63 | |||
| 64 | my $start_time = time(); | ||
| 65 | |||
| 66 | # Intercept send to add runtime header | ||
| 67 | my $wrapped_send = async sub { | ||
| 68 | my ($event) = @_; | ||
| 69 | if ($event->{type} eq 'http.response.start') { | ||
| 70 | my $duration = time() - $start_time; | ||
| 71 | my $formatted = sprintf('%.*f', $self->{precision}, $duration); | ||
| 72 | push @{$event->{headers}}, [$self->{header}, $formatted]; | ||
| 73 | } | ||
| 74 | await $send->($event); | ||
| 75 | }; | ||
| 76 | |||
| 77 | await $app->($scope, $receive, $wrapped_send); | ||
| 78 | }; | ||
| 79 | } | ||
| 80 | |||
| 81 | 1; | ||
| 82 | |||
| 83 | __END__ |