Extract send command logic from AUTOLOAD; make it more robust
authorPedro Melo <melo@simplicidade.org>
Wed, 4 Aug 2010 19:30:18 +0000 (20:30 +0100)
committerPedro Melo <melo@simplicidade.org>
Wed, 4 Aug 2010 19:30:18 +0000 (20:30 +0100)
We deal with partial writes now. Usually you won't notice the need until
you hit a very active client against a very loaded server.

Signed-off-by: Pedro Melo <melo@simplicidade.org>
lib/Redis.pm

index 3be91ff..a764584 100644 (file)
@@ -69,17 +69,8 @@ sub AUTOLOAD {
 
        my $command = $AUTOLOAD;
        $command =~ s/.*://;
-       warn "[SEND] $command ",Dumper([@_]) if $deb;
 
-       my $n_elems = scalar(@_)+1;
-       my $send = "\*$n_elems\r\n";
-       for my $str (uc($command), @_) {
-         my $bin = $enc? encode($enc, $str) : $str;
-         $send .= defined($bin)? '$'.length($bin)."\r\n$bin\r\n" : "\$-1\r\n";
-       }
-
-       warn "[SEND RAW] $send" if $deb;
-       print $sock $send;
+       $self->__send_command($command, @_);
 
        if ( $command eq 'quit' ) {
                close( $sock ) || confess("Can't close socket: $!");
@@ -123,6 +114,38 @@ sub AUTOLOAD {
        }
 }
 
+
+### Socket operations
+
+sub __send_command {
+  my $self = shift;
+  my $cmd  = uc(shift);
+  my $enc  = $self->{encoding};
+  my $deb  = $self->{debug};
+
+  warn "[SEND] $cmd ", Dumper([@_]) if $deb;
+
+  ## Encode command using multi-bulk format
+  my $n_elems = scalar(@_) + 1;
+  my $buf     = "\*$n_elems\r\n";
+  for my $elem ($cmd, @_) {
+    my $bin = $enc ? encode($enc, $elem) : $elem;
+    $buf .= defined($bin) ? '$' . length($bin) . "\r\n$bin\r\n" : "\$-1\r\n";
+  }
+
+  ## Send command, take care for partial writes
+  warn "[SEND RAW] $buf" if $deb;
+  my $sock = $self->{sock} || confess("Not connected to any server");
+  while ($buf) {
+    my $len = syswrite $sock, $buf, length $buf;
+    confess("Could not write to Redis server: $!")
+      unless $len;
+    substr $buf, 0, $len, "";
+  }
+
+  return;
+}
+
 sub __read_bulk {
        my ($self,$len) = @_;
        return if $len < 0;