package CloudStore::Gearman;
use warnings;
use strict;

use Gearman::XS qw(:constants);
use Gearman::XS::Client;

use Data::Dump qw(dump);

sub gearman {
	my $client = Gearman::XS::Client->new;
	my $server = $ENV{GEARMAN} || '127.0.0.1:4730';
	$client->add_server(split(/:/,$server));
	warn "## new gearman client to $server pid $$\n";
	return $client;
}

sub gearman_do {
	my $self = shift @_;
	my $func = shift @_;
	my $body = join(' ', @_) . "\n";
	warn "## gearman_do $func ",dump($body),"\n";

	my $client = $self->gearman;

	my ( $ret, $result ) = $client->do( $func => $body );
	if ( $ret == GEARMAN_SUCCESS || $ret == GEARMAN_WORK_DATA ) { # shell gearman clients return WORK_DATA
		warn "##>> ",dump($result),$/ if $ENV{DEBUG};
	} else {
		warn "# ERROR $ret ", Gearman::XS::strerror($ret), " result=",dump($result);
	}
	return $result;
}

1;
