ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent-MP/MP.pm
(Generate patch)

Comparing AnyEvent-MP/MP.pm (file contents):
Revision 1.1 by root, Thu Jul 30 08:38:50 2009 UTC vs.
Revision 1.18 by root, Mon Aug 3 21:35:03 2009 UTC

4 4
5=head1 SYNOPSIS 5=head1 SYNOPSIS
6 6
7 use AnyEvent::MP; 7 use AnyEvent::MP;
8 8
9 NODE # returns this node identifier
10 $NODE # contains this node identifier
11
12 snd $port, type => data...;
13
14 rcv $port, smartmatch => $cb->($port, @msg);
15
16 # examples:
17 rcv $port2, ping => sub { snd $_[0], "pong"; 0 };
18 rcv $port1, pong => sub { warn "pong received\n" };
19 snd $port2, ping => $port1;
20
21 # more, smarter, matches (_any_ is exported by this module)
22 rcv $port, [child_died => $pid] => sub { ...
23 rcv $port, [_any_, _any_, 3] => sub { .. $_[2] is 3
24
9=head1 DESCRIPTION 25=head1 DESCRIPTION
10 26
27This module (-family) implements a simple message passing framework.
28
29Despite its simplicity, you can securely message other processes running
30on the same or other hosts.
31
32At the moment, this module family is severly brokena nd underdocumented,
33so do not use. This was uploaded mainly to resreve the CPAN namespace -
34stay tuned!
35
36=head1 CONCEPTS
37
38=over 4
39
40=item port
41
42A port is something you can send messages to with the C<snd> function, and
43you can register C<rcv> handlers with. All C<rcv> handlers will receive
44messages they match, messages will not be queued.
45
46=item port id - C<noderef#portname>
47
48A port id is always the noderef, a hash-mark (C<#>) as separator, followed
49by a port name (a printable string of unspecified format).
50
51=item node
52
53A node is a single process containing at least one port - the node
54port. You can send messages to node ports to let them create new ports,
55among other things.
56
57Initially, nodes are either private (single-process only) or hidden
58(connected to a master node only). Only when they epxlicitly "become
59public" can you send them messages from unrelated other nodes.
60
61=item noderef - C<host:port,host:port...>, C<id@noderef>, C<id>
62
63A noderef is a string that either uniquely identifies a given node (for
64private and hidden nodes), or contains a recipe on how to reach a given
65node (for public nodes).
66
67=back
68
69=head1 VARIABLES/FUNCTIONS
70
71=over 4
72
11=cut 73=cut
12 74
13package AnyEvent::MP; 75package AnyEvent::MP;
14 76
77use AnyEvent::MP::Base;
78
15use common::sense; 79use common::sense;
16 80
81use Carp ();
82
17use AE (); 83use AE ();
18 84
85use base "Exporter";
86
19our $VERSION = '0.0'; 87our $VERSION = '0.02';
88our @EXPORT = qw(
89 NODE $NODE $PORT snd rcv mon del _any_
90 create_port create_port_on
91 create_miniport
92 become_slave become_public
93);
20 94
21sub nonce($) { 95=item NODE / $NODE
22 my $nonce;
23 96
24 if (open my $fh, "</dev/urandom") { 97The C<NODE ()> function and the C<$NODE> variable contain the noderef of
25 sysread $fh, $nonce, $_[0]; 98the local node. The value is initialised by a call to C<become_public> or
99C<become_slave>, after which all local port identifiers become invalid.
100
101=item snd $portid, type => @data
102
103=item snd $portid, @msg
104
105Send the given message to the given port ID, which can identify either
106a local or a remote port, and can be either a string or soemthignt hat
107stringifies a sa port ID (such as a port object :).
108
109While the message can be about anything, it is highly recommended to use a
110string as first element (a portid, or some word that indicates a request
111type etc.).
112
113The message data effectively becomes read-only after a call to this
114function: modifying any argument is not allowed and can cause many
115problems.
116
117The type of data you can transfer depends on the transport protocol: when
118JSON is used, then only strings, numbers and arrays and hashes consisting
119of those are allowed (no objects). When Storable is used, then anything
120that Storable can serialise and deserialise is allowed, and for the local
121node, anything can be passed.
122
123=item mon $portid, sub { }
124
125#TODO monitor the given port
126
127=cut
128
129sub mon {
130 my ($noderef, $port) = split /#/, shift, 2;
131
132 my $node = AnyEvent::MP::Base::add_node $noderef;
133
134 my $cb = shift;
135
136 $node->monitor ($port, $cb);
137
138 defined wantarray
139 and AnyEvent::Util::guard { $node->unmonitor ($port, $cb) }
140}
141
142=item $local_port = create_port
143
144Create a new local port object. See the next section for allowed methods.
145
146=cut
147
148sub create_port {
149 my $id = "$AnyEvent::MP::Base::UNIQ." . $AnyEvent::MP::Base::ID++;
150
151 my $self = bless {
152 id => "$NODE#$id",
153 names => [$id],
154 }, "AnyEvent::MP::Port";
155
156 $AnyEvent::MP::Base::PORT{$id} = sub {
157 unshift @_, $self;
158
159 for (@{ $self->{rc0}{$_[1]} }) {
160 $_ && &{$_->[0]}
161 && undef $_;
162 }
163
164 for (@{ $self->{rcv}{$_[1]} }) {
165 $_ && [@_[1 .. @{$_->[1]}]] ~~ $_->[1]
166 && &{$_->[0]}
167 && undef $_;
168 }
169
170 for (@{ $self->{any} }) {
171 $_ && [@_[0 .. $#{$_->[1]}]] ~~ $_->[1]
172 && &{$_->[0]}
173 && undef $_;
174 }
175 };
176
177 $self
178}
179
180=item $portid = miniport { my @msg = @_; $finished }
181
182Creates a "mini port", that is, a very lightweight port without any
183pattern matching behind it, and returns its ID.
184
185The block will be called for every message received on the port. When the
186callback returns a true value its job is considered "done" and the port
187will be destroyed. Otherwise it will stay alive.
188
189The message will be passed as-is, no extra argument (i.e. no port id) will
190be passed to the callback.
191
192If you need the local port id in the callback, this works nicely:
193
194 my $port; $port = miniport {
195 snd $otherport, reply => $port;
196 };
197
198=cut
199
200sub miniport(&) {
201 my $cb = shift;
202 my $id = "$AnyEvent::MP::Base::UNIQ." . $AnyEvent::MP::Base::ID++;
203
204 $AnyEvent::MP::Base::PORT{$id} = sub {
205 &$cb
206 and delete $AnyEvent::MP::Base::PORT{$id};
207 };
208
209 "$NODE#$id"
210}
211
212package AnyEvent::MP::Port;
213
214=back
215
216=head1 METHODS FOR PORT OBJECTS
217
218=over 4
219
220=item "$port"
221
222A port object stringifies to its port ID, so can be used directly for
223C<snd> operations.
224
225=cut
226
227use overload
228 '""' => sub { $_[0]{id} },
229 fallback => 1;
230
231sub TO_JSON { $_[0]{id} }
232
233=item $port->rcv (type => $callback->($port, @msg))
234
235=item $port->rcv ($smartmatch => $callback->($port, @msg))
236
237=item $port->rcv ([$smartmatch...] => $callback->($port, @msg))
238
239Register a callback on the given port.
240
241The callback has to return a true value when its work is done, after
242which is will be removed, or a false value in which case it will stay
243registered.
244
245If the match is an array reference, then it will be matched against the
246first elements of the message, otherwise only the first element is being
247matched.
248
249Any element in the match that is specified as C<_any_> (a function
250exported by this module) matches any single element of the message.
251
252While not required, it is highly recommended that the first matching
253element is a string identifying the message. The one-string-only match is
254also the most efficient match (by far).
255
256=cut
257
258sub rcv($@) {
259 my ($self, $match, $cb) = @_;
260
261 if (!ref $match) {
262 push @{ $self->{rc0}{$match} }, [$cb];
263 } elsif (("ARRAY" eq ref $match && !ref $match->[0])) {
264 my ($type, @match) = @$match;
265 @match
266 ? push @{ $self->{rcv}{$match->[0]} }, [$cb, \@match]
267 : push @{ $self->{rc0}{$match->[0]} }, [$cb];
26 } else { 268 } else {
27 # shit... 269 push @{ $self->{any} }, [$cb, $match];
28 our $nonce_init;
29 unless ($nonce_init++) {
30 srand time ^ $$ ^ unpack "%L*", qx"ps -edalf" . qx"ipconfig /all";
31 }
32
33 $nonce = join "", map +(chr rand 256), 1 .. $_[0]
34 } 270 }
35
36 $nonce
37} 271}
38 272
39our $DEFAULT_SECRET; 273=item $port->register ($name)
40 274
41sub default_secret { 275Registers the given port under the well known name C<$name>. If the name
42 unless (defined $DEFAULT_SECRET) { 276already exists it is replaced.
43 if (open my $fh, "<$ENV{HOME}/.aemp-secret") {
44 sysread $fh, $DEFAULT_SECRET, -s $fh;
45 } else {
46 $DEFAULT_SECRET = nonce 32;
47 }
48 }
49 277
50 $DEFAULT_SECRET 278A port can only be registered under one well known name.
279
280=cut
281
282sub register {
283 my ($self, $name) = @_;
284
285 $self->{wkname} = $name;
286 $AnyEvent::MP::Base::WKP{$name} = "$self";
51} 287}
288
289=item $port->destroy
290
291Explicitly destroy/remove/nuke/vaporise the port.
292
293Ports are normally kept alive by there mere existance alone, and need to
294be destroyed explicitly.
295
296=cut
297
298sub destroy {
299 my ($self) = @_;
300
301 AnyEvent::MP::Base::del $self->{id};
302
303 delete $AnyEvent::MP::Base::WKP{ $self->{wkname} };
304
305 delete $AnyEvent::MP::Base::PORT{$_}
306 for @{ $self->{names} };
307}
308
309=back
310
311=head1 FUNCTIONS FOR NODES
312
313=over 4
314
315=item mon $noderef, $callback->($noderef, $status, $)
316
317Monitors the given noderef.
318
319=item become_public endpoint...
320
321Tells the node to become a public node, i.e. reachable from other nodes.
322
323If no arguments are given, or the first argument is C<undef>, then
324AnyEvent::MP tries to bind on port C<4040> on all IP addresses that the
325local nodename resolves to.
326
327Otherwise the first argument must be an array-reference with transport
328endpoints ("ip:port", "hostname:port") or port numbers (in which case the
329local nodename is used as hostname). The endpoints are all resolved and
330will become the node reference.
331
332=cut
333
334=back
335
336=head1 NODE MESSAGES
337
338Nodes understand the following messages sent to them. Many of them take
339arguments called C<@reply>, which will simply be used to compose a reply
340message - C<$reply[0]> is the port to reply to, C<$reply[1]> the type and
341the remaining arguments are simply the message data.
342
343=over 4
344
345=cut
346
347=item wkp => $name, @reply
348
349Replies with the port ID of the specified well-known port, or C<undef>.
350
351=item devnull => ...
352
353Generic data sink/CPU heat conversion.
354
355=item relay => $port, @msg
356
357Simply forwards the message to the given port.
358
359=item eval => $string[ @reply]
360
361Evaluates the given string. If C<@reply> is given, then a message of the
362form C<@reply, $@, @evalres> is sent.
363
364Example: crash another node.
365
366 snd $othernode, eval => "exit";
367
368=item time => @reply
369
370Replies the the current node time to C<@reply>.
371
372Example: tell the current node to send the current time to C<$myport> in a
373C<timereply> message.
374
375 snd $NODE, time => $myport, timereply => 1, 2;
376 # => snd $myport, timereply => 1, 2, <time>
377
378=back
52 379
53=head1 SEE ALSO 380=head1 SEE ALSO
54 381
55L<AnyEvent>. 382L<AnyEvent>.
56 383

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines