| 1 | # | ||
| 2 | # This file is part of Riak-Light | ||
| 3 | # | ||
| 4 | # This software is copyright (c) 2013 by Weborama. | ||
| 5 | # | ||
| 6 | # This is free software; you can redistribute it and/or modify it under | ||
| 7 | # the same terms as the Perl 5 programming language system itself. | ||
| 8 | # | ||
| 9 | ## no critic (RequireUseStrict, RequireUseWarnings) | ||
| 10 | package Riak::Light::Timeout::SelectOnRead; | ||
| 11 | { | ||
| 12 | $Riak::Light::Timeout::SelectOnRead::VERSION = '0.12'; | ||
| 13 | } | ||
| 14 | ## use critic | ||
| 15 | |||
| 16 | use POSIX qw(ETIMEDOUT ECONNRESET); | ||
| 17 | use IO::Select; | ||
| 18 | use Time::HiRes; | ||
| 19 | use Config; | ||
| 20 | use Carp; | ||
| 21 | use Moo; | ||
| 22 | use Types::Standard -types; | ||
| 23 | |||
| 24 | with 'Riak::Light::Timeout'; | ||
| 25 | |||
| 26 | # ABSTRACT: proxy to read/write using IO::Select as a timeout provider only for READ operations | ||
| 27 | |||
| 28 | has socket => ( is => 'ro', required => 1 ); | ||
| 29 | has in_timeout => ( is => 'ro', isa => Num, default => sub {0.5} ); | ||
| 30 | has out_timeout => ( is => 'ro', isa => Num, default => sub {0.5} ); | ||
| 31 | has select => ( is => 'ro', default => sub { IO::Select->new } ); | ||
| 32 | |||
| 33 | sub BUILD { | ||
| 34 | |||
| 35 | #carp "Should block in Write Operations, be careful"; | ||
| 36 | |||
| 37 | $_[0]->select->add( $_[0]->socket ); | ||
| 38 | } | ||
| 39 | |||
| 40 | sub DEMOLISH { | ||
| 41 | $_[0]->clean(); | ||
| 42 | } | ||
| 43 | |||
| 44 | sub clean { | ||
| 45 | $_[0]->select->remove( $_[0]->socket ); | ||
| 46 | $_[0]->socket->close; | ||
| 47 | $! = ETIMEDOUT; ## no critic (RequireLocalizedPunctuationVars) | ||
| 48 | } | ||
| 49 | |||
| 50 | sub is_valid { | ||
| 51 | scalar $_[0]->select->handles; | ||
| 52 | } | ||
| 53 | |||
| 54 | sub sysread { | ||
| 55 | my $self = shift; | ||
| 56 | $self->is_valid | ||
| 57 | or $! = ECONNRESET, | ||
| 58 | return; ## no critic (RequireLocalizedPunctuationVars) | ||
| 59 | |||
| 60 | return $self->socket->sysread(@_) | ||
| 61 | if $self->select->can_read( $self->in_timeout ); | ||
| 62 | |||
| 63 | $self->clean(); | ||
| 64 | |||
| 65 | undef; | ||
| 66 | } | ||
| 67 | |||
| 68 | sub syswrite { | ||
| 69 | my $self = shift; | ||
| 70 | $self->is_valid | ||
| 71 | or $! = ECONNRESET, | ||
| 72 | return; ## no critic (RequireLocalizedPunctuationVars) | ||
| 73 | $self->socket->syswrite(@_); | ||
| 74 | } | ||
| 75 | |||
| 76 | 1; | ||
| 77 | |||
| 78 | |||
| 79 | __END__ |