6565e30723bdf3b71e6ca85a9e21fe8ae9e2a1de
[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 sub req {
77         my ( $self, $type, $data ) = @_;
78
79         Mojo::Util::encode($self->encoding, $data) if $self->encoding;
80
81         my $ret;
82
83         my $cb = sub {
84                 my ( $self, $data ) = @_;
85                 $self->ioloop->stop;
86                 warn "# <<<< ",dump($data);
87                 my ($magic, $type, $len) = unpack( "a4NN", $data );
88                 die "wrong magic [$magic]" unless $magic eq "\0RES";
89                 $ret = $data;
90         };
91
92         $data .= "\x00";
93         my $len = length($data);
94         my $message = pack("a4NN", "\0REQ", 16, length $data ) . $data;
95         warn "# >>>> ",dump($data);
96
97         my $mqueue = $self->{_message_queue} ||= [];
98         my $cqueue = $self->{_cb_queue}   ||= [];
99
100
101         push @$mqueue, $message;
102         push @$cqueue, $cb;
103
104         $self->connect unless $self->{_connection};
105         $self->_send_next_message;
106
107         $self->ioloop->start;
108
109         return $ret;
110 }
111
112 sub start {
113         my ($self) = @_;
114
115         $self->ioloop->start;
116         return $self;
117 }
118
119 sub stop {
120         my ($self) = @_;
121
122         $self->ioloop->stop;
123         return $self;
124 }
125
126 sub _send_next_message {
127         my ($self) = @_;
128
129         if ((my $c = $self->{_connection}) && !$self->{_connecting}) {
130                 while (my $message = shift @{$self->{_message_queue}}) {
131                 warn "# write ",dump($message);
132                 $self->ioloop->write($c, $message);
133                 }
134         }
135 }
136
137 sub _on_connect {
138         my ($self, $ioloop, $id) = @_;
139         delete $self->{_connecting};
140
141         $ioloop->connection_timeout($id => $self->timeout);
142
143         $self->_send_next_message;
144 }
145
146 sub _on_error {
147         my ($self, $ioloop, $id, $error) = @_;
148
149         $self->error($error);
150         $self->_inform_queue;
151
152         $self->on_error->($self);
153
154         $ioloop->drop($id);
155 }
156
157 sub _on_hup {
158         my ($self, $ioloop, $id) = @_;
159
160         $self->{error} ||= 'disconnected';
161         $self->_inform_queue;
162
163         delete $self->{_message_queue};
164
165         delete $self->{_connecting};
166         delete $self->{_connection};
167 }
168
169 sub _inform_queue {
170         my ($self) = @_;
171
172         for my $cb (@{$self->{_cb_queue}}) {
173                 $cb->($self) if $cb;
174         }
175         $self->{_queue} = [];
176 }
177
178 sub _on_read {
179         my ($self, $ioloop, $id, $data) = @_;
180
181         my $cb = shift @{$self->{_cb_queue}};
182         if ($cb) {
183                 Mojo::Util::decode($self->encoding, $data) if $data;
184                 warn "# on read callback with ", dump($data);
185                 $cb->($self, $data);
186         } else {
187                 warn "no callback";
188         }
189
190         # Reset error after callback dispatching
191         $self->error(undef);
192 }
193
194 1;
195 __END__
196
197 =head1 NAME
198
199 MojoX::Gearman - asynchronous Gearman client for L<Mojolicious>.
200
201 =head1 SYNOPSIS
202
203         use MojoX::Gearman;
204
205         my $gearman = MojoX::Gearman->new(server => '127.0.0.1:4730');
206
207 =head1 DESCRIPTION
208
209 L<MojoX::Gearman> is an asynchronous client to Gearman for Mojo.
210
211 =head1 ATTRIBUTES
212
213 L<MojoX::Gearman> implements the following attributes.
214
215 =head2 C<server>
216
217         my $server = $gearman->server;
218         $gearman         = $gearman->server('127.0.0.1:4730');
219
220 C<Gearman> server connection string, defaults to '127.0.0.1:4730'.
221
222 =head2 C<ioloop>
223
224         my $ioloop = $gearman->ioloop;
225         $gearman         = $gearman->ioloop(Mojo::IOLoop->new);
226
227 Loop object to use for io operations, by default a L<Mojo::IOLoop> singleton
228 object will be used.
229
230 =head2 C<timeout>
231
232         my $timeout = $gearman->timeout;
233         $gearman          = $gearman->timeout(100);
234
235 Maximum amount of time in seconds a connection can be inactive before being
236 dropped, defaults to C<300>.
237
238 =head2 C<encoding>
239
240         my $encoding = $gearman->encoding;
241         $gearman           = $gearman->encoding('UTF-8');
242
243 Encoding used for stored data, defaults to C<UTF-8>.
244
245 =head1 METHODS
246
247 =head2 C<req>
248
249         $gearman->req( $type, $data );
250
251 =head2 C<error>
252
253         $gearman->execute("ping" => sub {
254                 my ($gearman, $result) = @_;
255                 die $gearman->error unless defined $result;
256         }
257
258 Returns error occured during command execution.
259 Note that this method returns error code just from current command and
260 can be used just in callback.
261
262 =head2 C<on_error>
263
264         $gearman->on_error(sub{
265                 my $gearman = shift;
266                 warn 'Gearman error ', $gearman->error, "\n";
267         });
268
269 Executes if error occured. Called before commands callbacks.
270
271 =head2 C<start>
272
273         $gearman->start;
274
275 Starts IOLoop. Shortcut for $gearman->ioloop->start;
276
277 =head1 SEE ALSO
278
279 L<Gearman::Client>, L<Mojolicious>, L<Mojo::IOLoop>
280
281 =head1 SUPPORT
282
283 =head1 DEVELOPMENT
284
285 =head2 Repository
286
287         https://github.com/dpavlin/mojox-gearman
288
289 =head1 AUTHOR
290
291 Dobrica Pavlinusic, C<dpavlin@rot13.org>.
292
293 =head1 COPYRIGHT AND LICENSE
294
295 Copyright (C) 2010, Dobrica Pavlinusic
296
297 This program is free software, you can gearmantribute it and/or modify it under
298 the terms of the Artistic License version 2.0.
299
300 =cut