Add initial support for subscriber mode:
authorPedro Melo <melo@simplicidade.org>
Thu, 5 Aug 2010 16:44:54 +0000 (17:44 +0100)
committerPedro Melo <melo@simplicidade.org>
Thu, 5 Aug 2010 22:46:02 +0000 (23:46 +0100)
When we use any of SUBSCRIBE commands, we need to restrict the
commands we can use after. Only other SUBSCRIBE, or UNSUBSCRIBE commands
are valid.

We added a "mode", is_subscriber, that default to 0 and will be true after
we subscribe something. When is_subscriber is active, invalid commands
will result in an exception.

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

index b07bee6..151f7ce 100644 (file)
@@ -54,6 +54,8 @@ sub new {
                Proto => 'tcp',
        ) || confess("Could not connect to Redis server at $self->{server}: $!");
        $self->{rbuf} = '';
+       
+       $self->{is_subscriber} = 0;
 
        return bless($self, $class);
 }
@@ -73,6 +75,7 @@ sub AUTOLOAD {
 
        my $command = $AUTOLOAD;
        $command =~ s/.*://;
+       $self->__is_valid_command($command);
 
        $self->__send_command($command, @_);
 
@@ -94,6 +97,7 @@ sub quit {
 
 sub info {
   my ($self) = @_;
+  $self->__is_valid_command('INFO');
 
   $self->__send_command('INFO');
 
@@ -106,6 +110,7 @@ sub info {
 
 sub keys {
   my $self = shift;
+  $self->__is_valid_command('KEYS');
 
   $self->__send_command('KEYS', @_);
 
@@ -118,6 +123,16 @@ sub keys {
 }
 
 
+### Mode validation
+sub __is_valid_command {
+  my ($self, $cmd) = @_;
+
+  return unless $self->{is_subscriber};
+  return if $cmd =~ /^P?(UN)?SUBSCRIBE$/;
+  confess("Cannot use command '$cmd' while in SUBSCRIBE mode, ");
+}
+
+
 ### Socket operations
 sub __send_command {
   my $self = shift;