512a64171044e6bedcf185889d2c57d25f84f07b
[MojoX-Gearman.git] / lib / MojoX / Gearman.pm
1 package MojoX::Gearman;
2
3 use strict;
4 use warnings;
5
6 our $VERSION = 0.1;
7 use base 'Mojo::Base';
8
9 use Mojo::IOLoop;
10 use List::Util    ();
11 use Mojo::Util    ();
12 use Scalar::Util        ();
13 use Data::Dump qw(dump);
14 require Carp;
15
16 __PACKAGE__->attr(server   => '127.0.0.1:4730');
17 __PACKAGE__->attr(ioloop   => sub { Mojo::IOLoop->new });
18 __PACKAGE__->attr(error => undef);
19 __PACKAGE__->attr(timeout  => 300);
20 __PACKAGE__->attr(encoding => 'UTF-8');
21 __PACKAGE__->attr(
22         on_error => sub {
23                 sub {
24                         my $gearman = shift;
25                         warn "Gearman error: ", $gearman->error, "\n";
26                   }
27         }
28 );
29 __PACKAGE__->attr(res => undef);
30
31 sub DESTROY {
32         my $self = shift;
33
34         # Loop
35         return unless my $loop = $self->ioloop;
36
37         # Cleanup connection
38         $loop->drop($self->{_connection})
39           if $self->{_connection};
40 }
41
42 sub connect {
43         my $self = shift;
44
45         # drop old connection
46         if ($self->connected) {
47                 $self->ioloop->drop($self->{_connection});
48         }
49
50         $self->server =~ m{^([^:]+)(:(\d+))?};
51         my $address = $1;
52         my $port = $3 || 4730;
53
54         Scalar::Util::weaken $self;
55
56         # connect
57         $self->{_connecting} = 1;
58         $self->{_connection} = $self->ioloop->connect(
59                 {   address     => $address,
60                         port       => $port,
61                         on_connect => sub { $self->_on_connect(@_) },
62                         on_read => sub { $self->_on_read(@_) },
63                         on_error   => sub { $self->_on_error(@_) },
64                         on_hup   => sub { $self->_on_hup(@_) },
65                 }
66         );
67
68         warn "# using gearman server $address:$port\n";
69
70         return $self;
71 }
72
73 sub connected {
74         my $self = shift;
75
76         return $self->{_connection};
77 }
78
79 my $packet_type = {
80         TEXT => -1,     # fake type for text protocol
81
82         CAN_DO => 1,
83
84         PRE_SLEEP => 4,
85
86         NOOP => 6,
87
88         SUBMIT_JOB => 7,
89         JOB_CREATED => 8,
90
91         GRAB_JOB => 9,
92         NO_JOB => 10,
93         JOB_ASSIGN => 11,
94
95         WORK_COMPLETE => 13,
96         WORK_FAIL => 14,
97
98         ECHO_REQ => 16,
99         ECHO_RES => 17,
100
101         ERROR => 19,
102 };
103
104 my $nr2type;
105 $nr2type->{ $packet_type->{$_} } = $_ foreach keys %$packet_type;
106
107
108 sub parse_packet {
109         my ($self,$data) = @_;
110         die "no data in packet" unless $data;
111         my ($magic, $type, $len) = unpack( "a4NN", $data );
112         die "wrong magic [$magic]" unless $magic eq "\0RES";
113         die "unsupported type [$type]" unless exists $nr2type->{$type};
114         die "ERROR" if $type == $packet_type->{ERROR};
115         return ( $type, split("\0", substr($data,12,$len)) );
116 }
117
118 sub req {
119         my $self = shift;
120 warn "XXX req ",dump(@_);
121         my $type = shift;
122         my $callback = pop @_ if ref $_[$#_] eq 'CODE';
123         my $data = join("\0", @_);
124
125         die "can't find packet type $type in ", dump $packet_type unless exists $packet_type->{$type};
126         Mojo::Util::encode($self->encoding, $data) if $self->encoding;
127
128         $self->{_res} = undef;
129
130         my $response;
131         my $cb = sub {
132                 my ( $self, $data ) = @_;
133
134                 if ( substr($data,0,1) ne "\x00" ) {
135                         $self->res( $data );
136                         $self->stop;
137                         return;
138                 }
139
140                 my ( $type, @data ) = $self->parse_packet($data);
141                 warn "# <<<< ", $nr2type->{$type}, " ",dump(@data);
142
143                 if ( $type == $packet_type->{JOB_CREATED} ) {
144                         push @{ $self->{_cb_queue} }, sub {
145                                 my ( $self,$data ) = @_;
146                                 my ( $type, $handle, $out ) = $self->parse_packet($data);
147 warn "# <<<< ",$nr2type->{$type}, " ",dump $data;
148                                 if ( $type == $packet_type->{WORK_COMPLETE} ) {
149                                         warn "WORK_COMPLETE $handle ", dump $out;
150                                 } elsif ( $type == $packet_type->{WORK_FAIL} ) {
151                                         warn "WORK_FAIL $handle ", dump $out;
152                                 }
153                                 $self->res( $out );
154                                 $self->stop;
155                         };
156                 } elsif ( $type == $packet_type->{NO_JOB} ) {
157                         $self->req( 'PRE_SLEEP' );
158                         $self->stop;
159                 } elsif ( $type == $packet_type->{JOB_ASSIGN} ) {
160                         my ( $handle, $function, $workload ) = @data;
161                         my $callback = $self->{_function}->{$function};
162                         die "no $function callback" unless ref $callback eq 'CODE';
163                         my $out = $callback->( $workload );
164                         warn "## $data $callback = ", dump $out;
165                         $self->req( 'WORK_COMPLETE', $handle, $out );
166                         $self->req( 'GRAB_JOB' );
167                 } elsif ( $type == $packet_type->{NOOP} ) {
168                         $self->req( 'GRAB_JOB' );
169                 } else {
170                         $self->stop;
171                 }
172
173                 my $out = $#data == 0 ? $data[0] : [ @data ];
174                 $self->res( $out );
175
176         };
177
178 #       $data .= "\0" if $data;
179         my $len = length($data);
180         my $message = $type ne 'TEXT'
181                 ? pack("a4NN", "\0REQ", $packet_type->{$type}, length $data ) . $data
182                 : "$data\r\n"
183         ;
184         warn "# >>>> $type ",dump($message);
185
186         my $mqueue = $self->{_message_queue} ||= [];
187         my $cqueue = $self->{_cb_queue}   ||= [];
188
189         push @$mqueue, $message;
190         push @$cqueue, $cb;
191
192         $self->connect unless $self->{_connection};
193         $self->_send_next_message;
194
195         if ( $type eq 'CAN_DO' ) {
196                 $self->{_function}->{$data} = $callback;
197                 $self->res( $callback );
198                 warn "# installed $data callback $callback";
199         } elsif ( $type =~ m/^(ECHO_REQ|SUBMIT_JOB|GRAB_JOB|TEXT)$/ ) { # sync commands
200                 $self->start;
201         }
202
203         $self->res;
204 }
205
206 sub start {
207         my ($self) = @_;
208         warn "# start";
209         $self->ioloop->start;
210         return $self;
211 }
212
213 sub stop {
214         my ($self) = @_;
215         warn "# stop";
216         $self->ioloop->stop;
217         return $self;
218 }
219
220 sub _send_next_message {
221         my ($self) = @_;
222
223         if ((my $c = $self->{_connection}) && !$self->{_connecting}) {
224                 while (my $message = shift @{$self->{_message_queue}}) {
225                         warn "# write ",dump($message);
226                         $self->ioloop->write($c, $message);
227                 }
228         }
229 }
230
231 sub _on_connect {
232         my ($self, $ioloop, $id) = @_;
233         delete $self->{_connecting};
234
235         $ioloop->connection_timeout($id => $self->timeout);
236
237         $self->_send_next_message;
238 }
239
240 sub _on_error {
241         my ($self, $ioloop, $id, $error) = @_;
242
243         warn "ERROR: $error";
244
245         $self->error($error);
246         $self->_inform_queue;
247
248         $self->on_error->($self);
249
250         $ioloop->drop($id);
251 }
252
253 sub _on_hup {
254         my ($self, $ioloop, $id) = @_;
255
256         $self->{error} ||= 'disconnected';
257         $self->_inform_queue;
258
259         delete $self->{_message_queue};
260
261         delete $self->{_connecting};
262         delete $self->{_connection};
263 }
264
265 sub _inform_queue {
266         my ($self) = @_;
267
268         for my $cb (@{$self->{_cb_queue}}) {
269                 $cb->($self) if $cb;
270         }
271         $self->{_queue} = [];
272 }
273
274 sub _on_read {
275         my ($self, $ioloop, $id, $data) = @_;
276
277         warn "<<<< _on_read ",dump( $id, $data );
278
279         $data = $self->{message}->{$id} .= $data;
280         my ($magic, $type, $len) = unpack( "a4NN", $data );
281
282         if ( substr($data,0,1) ne "\x00" ) {
283                 return if $data !~ s/\.[\n\r]$//s;
284         } elsif ( length $data < $len ) {
285                 warn "# _on_read incomplete message";
286                 return;
287         }
288
289         warn "#### data ",dump($data);
290
291         my $cb = shift @{$self->{_cb_queue}};
292         if ($cb) {
293 #               Mojo::Util::decode($self->encoding, $data) if $data; # FIXME
294                 warn "# on read callback with ", dump($data);
295                 $cb->($self, $data);
296         } else {
297                 warn "no callback";
298         }
299
300         delete $self->{message}->{$id};
301
302         # Reset error after callback dispatching
303         $self->error(undef);
304 }
305
306 1;
307 __END__
308
309 =head1 NAME
310
311 MojoX::Gearman - asynchronous Gearman client for L<Mojolicious>.
312
313 =head1 SYNOPSIS
314
315         use MojoX::Gearman;
316
317         my $gearman = MojoX::Gearman->new(server => '127.0.0.1:4730');
318
319 =head1 DESCRIPTION
320
321 L<MojoX::Gearman> is an asynchronous client to Gearman for Mojo.
322
323 =head1 ATTRIBUTES
324
325 L<MojoX::Gearman> implements the following attributes.
326
327 =head2 C<server>
328
329         my $server = $gearman->server;
330         $gearman         = $gearman->server('127.0.0.1:4730');
331
332 C<Gearman> server connection string, defaults to '127.0.0.1:4730'.
333
334 =head2 C<ioloop>
335
336         my $ioloop = $gearman->ioloop;
337         $gearman         = $gearman->ioloop(Mojo::IOLoop->new);
338
339 Loop object to use for io operations, by default a L<Mojo::IOLoop> singleton
340 object will be used.
341
342 =head2 C<timeout>
343
344         my $timeout = $gearman->timeout;
345         $gearman          = $gearman->timeout(100);
346
347 Maximum amount of time in seconds a connection can be inactive before being
348 dropped, defaults to C<300>.
349
350 =head2 C<encoding>
351
352         my $encoding = $gearman->encoding;
353         $gearman           = $gearman->encoding('UTF-8');
354
355 Encoding used for stored data, defaults to C<UTF-8>.
356
357 =head1 METHODS
358
359 =head2 C<req>
360
361         $gearman->req( $type, $data, ..., sub { # callback } );
362
363 =head2 C<error>
364
365         $gearman->execute("ping" => sub {
366                 my ($gearman, $result) = @_;
367                 die $gearman->error unless defined $result;
368         }
369
370 Returns error occured during command execution.
371 Note that this method returns error code just from current command and
372 can be used just in callback.
373
374 =head2 C<on_error>
375
376         $gearman->on_error(sub{
377                 my $gearman = shift;
378                 warn 'Gearman error ', $gearman->error, "\n";
379         });
380
381 Executes if error occured. Called before commands callbacks.
382
383 =head2 C<start>
384
385         $gearman->start;
386
387 Starts IOLoop. Shortcut for $gearman->ioloop->start;
388
389 =head1 SEE ALSO
390
391 L<Gearman::Client>, L<Mojolicious>, L<Mojo::IOLoop>
392
393 =head1 SUPPORT
394
395 =head1 DEVELOPMENT
396
397 =head2 Repository
398
399         https://github.com/dpavlin/mojox-gearman
400
401 =head1 AUTHOR
402
403 Dobrica Pavlinusic, C<dpavlin@rot13.org>.
404
405 =head1 COPYRIGHT AND LICENSE
406
407 Copyright (C) 2010, Dobrica Pavlinusic
408
409 This program is free software, you can gearmantribute it and/or modify it under
410 the terms of the Artistic License version 2.0.
411
412 =cut