Get Plack Session ID in background thread

254 views Asked by At

Sorry, I really tried but I can't find a solution to this simple problem.

I need to get id session in plack, but not via browser, I want to do internally background in main namespace perl plack code.

This is my code:

#!/usr/bin/perl 
use Plack::Builder;
use YAML;
use Plack::Session::Store::File;

my $app = sub {
    my $env = shift;
    #$global = 'write thsi text to file';
    $global = $env->{'psgix.session.options'}{id};
    return [ 200, [], [ "App session ID: " . $global ] ];
};
$app->();

open my $fileHandle, ">>", "file" or die "Can't open '\n";
print $fileHandle $global;
close $fileHandle;

my $id = sub {
    my $env = shift;
    return [ 200, [], [ 'The ID session is: ' . $global ] ];
};

builder {
    enable 'Session', store => Plack::Session::Store::File->new(
                dir => './sessiondir',
                serializer   => sub { YAML::DumpFile( reverse @_ ) },
                deserializer => sub { YAML::LoadFile( @_ ) },
            );
    mount '/id' => $id;
    mount '/' => $app;

};

If I visit the root path http://192.168.1.1:5000, I get:

App session ID: 33d2e5c9fc9d57ca79679675130d7a06b7ccc1f6

If I visit http://192.168.1.1:5000/id

The ID session is: 33d2e5c9fc9d57ca79679675130d7a06b7ccc1f6

I want to write the id session in the file from $global variable:

open my $fileHandle, ">>", "file" or die "Can't open '\n";
print $fileHandle $global;
close $fileHandle;

In the destination file I get nothing, but if I change to variable to this, it work:

#$global = 'write thsi text to file';

Maybe the problem is because this text:

Threads in the thread pool are managed by the system. These threads are not bound to the current request. Therefore, Session is not available for them.

Source: Can I access sessions in background thread?

My target is just get the id and open this file to do another things from background. I want to avoid to save another file to this simple task, avoid sql, etc.

Because I already save the data session in a file:

enable 'Session', store => Plack::Session::Store::File->new(
                dir => './sessiondir',
                serializer   => sub { YAML::DumpFile( reverse @_ ) },
                deserializer => sub { YAML::LoadFile( @_ ) },
            );

I appreciate any recommendation, maybe this is possible in another way.

Thanks so much.

0

There are 0 answers