AnyEvent-KVStore-Etcd
view release on metacpan or search on metacpan
lib/AnyEvent/KVStore/Etcd.pm view on Meta::CPAN
has cnx => (is => 'ro', builder => '_etcd_connect', lazy => 1);
=head1 METHODS
=head2 read
Reads a value from a key and returns a JSON document payload.
=cut
sub read($$) {
my ($self, $key) = @_;
my $value = $self->cnx->range({key => $key })->{response}->{content};
$value = decode_json($value)->{kvs}->[0]->{value};
return decode_base64($value);
}
=head2 exists
Checks to see if a key exists. Here this is no less costly than read.
=cut
sub exists($$) {
my ($self, $key) = @_;
my $value = $self->cnx->range({key => $key })->{response}->{content};
$value = decode_json($value)->{kvs}->[0]->{value};
return defined $value;;
}
=head2 list($pfx)
Returns a list of keys
=cut
# adds one to the binary representation of the string for prefix searches
sub _add_one($){
my ($str) = @_;
if ($str =~ /^\xff*$/){ # for empty string too
return "\x00";
}
my $inc = $str;
$inc =~ s/([^\xff])\xff*\z/ $1 =~ tr||\x01-\xff|cr /e;
return $inc;
}
sub list($$) {
my ($self, $pfx) = @_;
my $value = $self->cnx->range({key => $pfx, range_end => _add_one($pfx)})->{response}->{content};
return map { decode_base64($_->{key} ) } @{decode_json($value)->{kvs}};
}
=head2 write($key, $value)
Writes the key to the database and returns 1 if successful, 0 if not.
=cut
sub write($$$) {
my ($self, $key, $value) = @_;
return $self->cnx->put({ key => $key, value => $value })->is_success;
}
=head2 watch($pfx, $callback)
This sets up a "watch" where notifications of changed keys are passed to the
script. This can only really be handled inside an AnyEvent loop because the
changes can come from outside the program.
lib/AnyEvent/KVStore/Etcd.pm view on Meta::CPAN
sub _portability_wrapper {
my ($sub, $result) = @_;
use Data::Dumper;
for my $e (@{decode_json($result)->{result}->{events}}){
$e = $e->{kv};
&$sub(decode_base64($e->{key}), decode_base64($e->{value}));
}
}
sub watch($$$) {
my ($self, $pfx, $subroutine ) = @_;
return $self->cnx->watch({key => $pfx, range_end => _add_one($pfx)},
sub { my ($result) = @_; _portability_wrapper($subroutine, $result) })->create;
}
=head1 AUTHOR
Chris Travers, C<< <chris.travers at gmail.com> >>
( run in 0.811 second using v1.01-cache-2.11-cpan-65fba6d93b7 )