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