| 1 | package #hide | ||
| 2 | AnyEvent::Memcached::Conn; | ||
| 3 | |||
| 4 | use common::sense 2;m{ | ||
| 5 | use strict; | ||
| 6 | use warnings; | ||
| 7 | }x; | ||
| 8 | use base 'AnyEvent::Connection::Raw'; | ||
| 9 | use AnyEvent::Memcached; | ||
| 10 | use AnyEvent::Connection::Util; | ||
| 11 | |||
| 12 | our $NL = "\015\012"; | ||
| 13 | our $QRNL = qr<\015?\012>; | ||
| 14 | our $VERSION = $AnyEvent::Memcached::VERSION; | ||
| 15 | |||
| 16 | sub reader { | ||
| 17 | my ($self,%args) = @_; | ||
| 18 | $args{cb} or return $self->event( error => "no cb for command at @{[ (caller)[1,2] ]}" ); | ||
| 19 | $self->{h} or return $args{cb}->(undef,"Not connected"); | ||
| 20 | my $result = $args{res} || {}; | ||
| 21 | my $ar = ref $result eq 'ARRAY' ? 1 : 0; | ||
| 22 | my $cut = exists $args{namespace} ? length $args{namespace} : 0; | ||
| 23 | my $reader;$reader = sub { | ||
| 24 | shift; | ||
| 25 | defined( local $_ = shift ) or return $args{cb}(undef,@_); | ||
| 26 | warn "<<$args{id} $_" if $self->{debug}; | ||
| 27 | if ($_ eq "END") { | ||
| 28 | undef $reader; | ||
| 29 | $args{cb}( $result ); | ||
| 30 | } | ||
| 31 | elsif (substr($_,0,5) eq 'ERROR') { | ||
| 32 | undef $reader; | ||
| 33 | $args{cb}( undef, $_ ); | ||
| 34 | } | ||
| 35 | elsif (!length) { | ||
| 36 | warn "Skip empty line"; | ||
| 37 | $self->{h}->unshift_read( line => $reader); | ||
| 38 | } | ||
| 39 | elsif( /^VALUE (\S+) (\d+) (\d+)(?:| (.+))$/ ) { | ||
| 40 | my ($key,$flags,$len,$cas) = ($1,$2,$3,$4); | ||
| 41 | #warn "have to read $1 $2 $3 $4"; | ||
| 42 | $self->recv( $3+2 => cb => sub { | ||
| 43 | #shift; | ||
| 44 | my $data = shift; | ||
| 45 | substr($data,$len) = ''; # trim out data outside length | ||
| 46 | #$data = substr($data,0,length($data)-2); | ||
| 47 | $key = substr($key, $cut) if substr($key, 0, $cut) eq $args{namespace}; | ||
| 48 | warn "+ received data $key: $data" if $self->{debug}; | ||
| 49 | my $v = { | ||
| 50 | data => $data, | ||
| 51 | flags => $flags, | ||
| 52 | defined $cas ? (cas => $cas) : (), | ||
| 53 | }; | ||
| 54 | if ($ar) { | ||
| 55 | push @$result, $key, $v; | ||
| 56 | } else { | ||
| 57 | $result->{$key} = $v;#{ data => $data, $cas ? (cas => $cas) : () }; | ||
| 58 | } | ||
| 59 | |||
| 60 | $self->{h}->unshift_read( line => $reader); | ||
| 61 | }); | ||
| 62 | } | ||
| 63 | else { | ||
| 64 | die "Wrong data received: ".dumper($_)."($!)"; | ||
| 65 | #$args{cb}(undef,$_); | ||
| 66 | #$self->handle_errors($_); | ||
| 67 | } | ||
| 68 | }; | ||
| 69 | $self->{h}->push_read( line => $reader ); | ||
| 70 | } | ||
| 71 | |||
| 72 | |||
| 73 | 1; | ||
| 74 | |||
| 75 | 1; |