summaryrefslogtreecommitdiff
path: root/lib/Plack/Middleware/Transaction.pm
blob: 7432adbc6ddbd780a3e3a1b0126db8baac3eb5df (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package Plack::Middleware::Transaction;

use strict;
use warnings;

use Data::UUID::LibUUID;
use Sys::Hostname;

use parent qw/Plack::Middleware/;
use Plack::Util::Accessor qw/host/;

sub prepare_app {
    my $self = shift;
    $self->host(hostname());
}

sub call {
    my ( $self, $env ) = @_;

    my $uuid = new_uuid_string();

    my $revision = `git rev-parse HEAD` || undef;
    chomp $revision if ($revision);

    $self->response_cb(
        $self->app->($env),
        sub {
            my $res     = shift;
            my $headers = $res->[1];

            if ($self->host) {
                $self->logger( $env, "[$uuid] is running on host" . $self->host );
                Plack::Util::header_set( $headers, 'X-Hostname', $self->host );
            }

            if ($revision) {
                $self->logger( $env, "[$uuid] is on git revision " . $revision );
                Plack::Util::header_set( $headers, 'X-Revision', $revision );
            }

            $self->logger( $env, "[$uuid] Transaction completed" );
            Plack::Util::header_set( $headers, 'X-Transaction', $uuid );
            return $res;
        }
    );
}

sub logger {
    my ( $self, $env, $message ) = @_;

    if ( $env->{'psgix.logger'} ) {
        $env->{'psgix.logger'}->(
            {
                level   => 'info',
                message => $message,
            }
        );
    }
}

1;