#!/usr/bin/perl

package Cog; # persistant Gearman Worker - see the pun?

use Moose;
use JSON::XS qw();
extends 'Gearman::Driver::Worker::Base';

sub prefix { '' }

sub encode_json {
	my ( $self, $result ) = @_;
	return JSON::XS::encode_json($result);
}

sub decode_json {
	my ( $self, $workload ) = @_;
	return JSON::XS::decode_json($workload);
}

package main;

use Gearman::Driver;

my $driver = Gearman::Driver->new(
	server   => 'localhost:4730',
	interval => 60,
	loglevel   => 'DEBUG',
	logfile    => 'log/persistant.log',
) || die $!;

my $w1 = 'Cog';
my $worker = $w1->new();

$worker->meta->add_method( 'scale_image' => sub {
	my ( $self, $job, $workload ) = @_;
	warn "# scale_image $job $workload";
	# do something
	return { scale_image => $workload };
});


# run each method in an own process
foreach my $method (qw(scale_image )) {
	$driver->add_job(
		{
			max_processes => 5,
			min_processes => 1,
			name		=> $method,
			worker		=> $worker,
			methods	   => [
				{
					body   => $w1->meta->find_method_by_name($method)->body,
#					decode => 'decode_json',
					encode => 'encode_json',
					name   => $method,
				},
			]
		}
	);
}

$driver->run;

