| 1 | package Plack::Session::Store::KyotoTycoon; | ||
| 2 | |||
| 3 | use 5.010; | ||
| 4 | use Cache::KyotoTycoon; | ||
| 5 | use Try::Tiny; | ||
| 6 | use Storable qw/nfreeze thaw/; | ||
| 7 | use MIME::Base64 qw(encode_base64 decode_base64); | ||
| 8 | |||
| 9 | # ABSTRACT: Plack::Session storage for Kyoto Tycoon | ||
| 10 | |||
| 11 | our $VERSION = '0.1'; # VERSION | ||
| 12 | |||
| 13 | use parent 'Plack::Session::Store'; | ||
| 14 | |||
| 15 | |||
| 16 | sub new { | ||
| 17 | my ($class, %params) = @_; | ||
| 18 | |||
| 19 | $params{tycoon} = _verify_tycoon_connection; | ||
| 20 | |||
| 21 | return bless {%params} => $class; | ||
| 22 | } | ||
| 23 | |||
| 24 | |||
| 25 | sub fetch { | ||
| 26 | my ($self, $key) = @_; | ||
| 27 | |||
| 28 | my @data; | ||
| 29 | try { | ||
| 30 | @data = $self->{tycoon}->get($key); | ||
| 31 | } | ||
| 32 | catch { | ||
| 33 | $self->_verify_tycoon_connection; | ||
| 34 | @data = $self->{tycoon}->get($key); | ||
| 35 | }; | ||
| 36 | |||
| 37 | if (defined($data[0])) { | ||
| 38 | my $sess = thaw(decode_base64($data[0])); | ||
| 39 | $sess->{__expire} = $data[1]; | ||
| 40 | return $sess; | ||
| 41 | } | ||
| 42 | return; | ||
| 43 | } | ||
| 44 | |||
| 45 | |||
| 46 | sub store { | ||
| 47 | my ($self, $key, $data, $expire) = @_; | ||
| 48 | |||
| 49 | $data = encode_base64(nfreeze($data)); | ||
| 50 | $expire = 3600 unless $expire; | ||
| 51 | my $replace; | ||
| 52 | try { | ||
| 53 | $replace = $self->{tycoon}->replace($key, $data, $expire); | ||
| 54 | } | ||
| 55 | catch { | ||
| 56 | $self->_verify_tycoon_connection; | ||
| 57 | $replace = $self->{tycoon}->replace($key, $data, $expire); | ||
| 58 | }; | ||
| 59 | |||
| 60 | return $self->{tycoon}->set($key, $data, $expire) | ||
| 61 | unless $replace; | ||
| 62 | return; | ||
| 63 | } | ||
| 64 | |||
| 65 | |||
| 66 | sub remove { | ||
| 67 | my ($self, $key) = @_; | ||
| 68 | |||
| 69 | try { return $self->{tycoon}->remove($key); } | ||
| 70 | catch { | ||
| 71 | $self->_verify_tycoon_connection; | ||
| 72 | return $self->{tycoon}->remove($key); | ||
| 73 | } | ||
| 74 | return; | ||
| 75 | } | ||
| 76 | |||
| 77 | sub _verify_tycoon_connection { | ||
| 78 | my ($self) = @_; | ||
| 79 | |||
| 80 | try { $self->{tycoon}->echo({ test => 1 }); } | ||
| 81 | catch { | ||
| 82 | $self->{tycoon} = Cache::KyotoTycoon->new( | ||
| 83 | timeout => 2, | ||
| 84 | exists $self->{tycoon_server} | ||
| 85 | ? (host => $self->{tycoon_server}) | ||
| 86 | : (), | ||
| 87 | exists $self->{tycoon_port} ? (port => $self->{tycoon_port}) : (), | ||
| 88 | ); | ||
| 89 | }; | ||
| 90 | return; | ||
| 91 | } | ||
| 92 | |||
| 93 | |||
| 94 | 1; # End of Plack::Session::Store::KyotoTycoon | ||
| 95 | |||
| 96 | __END__ |