package Catalyst::Plugin::MyApp::TrackLeaks;

=head1 NAME

Catalyst::Plugin::MyApp::TrackLeaks

=head1 DESCRIPTION

trace the leaks in my app!

=head1 SYNOPSIS


    use Catalyst qw/ ... MyApp::TrackLeaks ... /;
    
    # reads value
    my $value = $c->mish_config( $name ); 
    
    # write
    $c->mish_config( $name, $value );
    
    
    
    package MyApp::Controller::Root;
    
    # ..
    
    sub begin : Private {
        my ( $self, $c ) = @_;
        # ..
        $c->start_proc_size_in_memory;
        # ..
    }
    
    # ...
    
    sub end : ActionClass('RenderView') {
        my ( $self, $c ) = @_;
        # ..
        $c->log->debug( $c->req->path .": ". $c->end_proc_size_in_memory );
        return ;
    }

=cut

use strict;
use warnings;

use Data::Dumper;
use Proc::ProcessTable;
use Number::Format;


=head1 METHODS

=head2 proc_size_in_memory

returns the size in memory of the current running process 

=cut

sub proc_size_in_memory {
    my ( $c ) = @_;
    my $pt = Proc::ProcessTable->new;
    my $pid = $$;
    foreach my $proc( @{ $pt->table } ) {
        if ( $proc->pid == $pid ) {
            my $size = $proc->size;
            undef $pt;
            return $size;
        }
    }
    
    return 0;
}



=head2 start_proc_size_in_memory

measures process size in memory and writes it to stash for later usage ..

=cut

sub start_proc_size_in_memory {
    my ( $c ) = @_;
    return $c->stash->{ _start_proc_size_in_memory } = $c->proc_size_in_memory;
}



=head2 end_proc_size_in_memory

returns formatted string with the size of bytes in memory  .. and the differene between start 

=cut

sub end_proc_size_in_memory {
    my ( $c ) = @_;
    
    my $end = $c->proc_size_in_memory;
    my $n = Number::Format->new( thousands_sep => ',', decimal_point => '.' );
    
    if ( defined ( my $start = $c->stash->{ _start_proc_size_in_memory } ) ) {
        return sprintf( '%s: Memory: from %s (%d) to %s (%d) diff %s (%d) [pid=%d]',
            $c->req->path ."",
            $n->format_bytes( $start ), $start,
            $n->format_bytes( $end ), $end,
            $n->format_bytes( $end - $start ), $end - $start,
            $$
        );
    }
    return sprintf( '%s: Memory: no start, but current %s (%d) [pid=%d]',
        $c->req->path. "", $n->format_bytes( $end ), $end, $$
    );
}


1;


