#===============================================================================
# why D2::Session::Simple sessions don't work propely with Starman
# Using sessions with perl Dancer/plack/Starman and multiple workers
# https://stackoverflow.com/questions/28920848/using-sessions-with-perl-dancer-plack-starman-and-multiple-workers
#===============================================================================
## plackup -workers 3 -R testcounter.pl -p 3001 -s Gazelle [-e 'enable Debug'] \
# testcounter.pl
# for speed profile: "ab -n 10000 http://127.0.0.1:3000/"
# using Simple sessions, Twiggy, Corona and default HTTP::Server::PSGI work OK,
# Gazelle & Starlet don't increment counter at all, Starman increments counter
# OK for delay between reloads of around 1 sec or less
# Cookie & CHI sessions OK for all servers
#### watch session ID change, or not, depending on server type, in console output
use Dancer2;
use HTML::Tiny; # 2009 module - doesn't produce valid HTML5
use Data::Printer;
use Carp qw(longmess);
{ # CHI/FastMmap config:
my $c = config;
$c->{engines}->{session}->{CHI}->{driver} = 'FastMmap'; # defaults OK
}
set session => 'Simple';
#set session => 'Cookie';
#set session => 'CHI';
my $stack = longmess("Stack:"); # p $stack;
my ($server) = $stack =~ /Plack::Handler::(\w+)/;
$server ||= 'unknown';
get '/:action?' => sub {
my $r = request; # p $r;
my $counter = session 'counter' || 0;
# if action = reset:
if ( my $action = route_parameters->get('action') ) { # p %ENV;
$counter = 0 if $action eq 'reset';
}
$counter++;
# p my $id = 'session id=' . session->id;
info 'SESSION COUNTER = ' . $counter;
session counter => $counter; # p my $s = session;
my $pid = $$; # p $pid;
return to_html({ server => $server, pid => $pid, n => $counter });
};
sub to_html {
my $href = shift;
my ($server, $n, $pid) = @{$href}{qw/server n pid/};
return qq~
<!DOCTYPE html>
<head>
<style>
body { font-family: Verdana, sans-serif }
.red { color: #f00 }
a { color: #00f; text-decoration: none }
</style>
</head>
<body>
<div>[Server: $server; pid: $pid]
<span class="red">counter: $n</span>
<a href="/">reload</a> :: <a href="/reset">reset</a>
</div>
</body>
</html>~;
=begin # HTML::Tiny - doesn't produce valid HTML5 as it's a 2009 module!
my $h = HTML::Tiny->new;
return $h->html(
[
$h->head(
$h->style( [ 'body { font-family: Verdana, sans-serif } ',
'a { color: #00f; text-decoration: none } ', '.red { color: #f00 }'
] )
),
$h->body(
[
$h->tag( div => [ "[Server: ${server}; pid: ${pid}] ",
$h->tag( span => {class => 'red'}, "counter: $n " ),
$h->tag( a => { href => '/' }, 'reload' ), ' :: ',
$h->tag( a => { href => '/reset' }, 'reset' )
])
]
)
]
);
=cut
}
dance;