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.22 by root, Tue Aug 4 18:33:30 2009 UTC vs.
Revision 1.32 by root, Wed Aug 5 19:58:46 2009 UTC

30This module (-family) implements a simple message passing framework. 30This module (-family) implements a simple message passing framework.
31 31
32Despite its simplicity, you can securely message other processes running 32Despite its simplicity, you can securely message other processes running
33on the same or other hosts. 33on the same or other hosts.
34 34
35For an introduction to this module family, see the L<AnyEvent::MP::Intro>
36manual page.
37
35At the moment, this module family is severly brokena nd underdocumented, 38At the moment, this module family is severly broken and underdocumented,
36so do not use. This was uploaded mainly to reserve the CPAN namespace - 39so do not use. This was uploaded mainly to reserve the CPAN namespace -
37stay tuned! 40stay tuned! The basic API should be finished, however.
38 41
39=head1 CONCEPTS 42=head1 CONCEPTS
40 43
41=over 4 44=over 4
42 45
43=item port 46=item port
44 47
45A port is something you can send messages to with the C<snd> function, and 48A port is something you can send messages to (with the C<snd> function).
46you can register C<rcv> handlers with. All C<rcv> handlers will receive 49
47messages they match, messages will not be queued. 50Some ports allow you to register C<rcv> handlers that can match specific
51messages. All C<rcv> handlers will receive messages they match, messages
52will not be queued.
48 53
49=item port id - C<noderef#portname> 54=item port id - C<noderef#portname>
50 55
51A port id is always the noderef, a hash-mark (C<#>) as separator, followed 56A port id is normaly the concatenation of a noderef, a hash-mark (C<#>) as
52by a port name (a printable string of unspecified format). 57separator, and a port name (a printable string of unspecified format). An
58exception is the the node port, whose ID is identical to its node
59reference.
53 60
54=item node 61=item node
55 62
56A node is a single process containing at least one port - the node 63A node is a single process containing at least one port - the node
57port. You can send messages to node ports to let them create new ports, 64port. You can send messages to node ports to find existing ports or to
58among other things. 65create new ports, among other things.
59 66
60Initially, nodes are either private (single-process only) or hidden 67Nodes are either private (single-process only), slaves (connected to a
61(connected to a master node only). Only when they epxlicitly "become 68master node only) or public nodes (connectable from unrelated nodes).
62public" can you send them messages from unrelated other nodes.
63 69
64=item noderef - C<host:port,host:port...>, C<id@noderef>, C<id> 70=item noderef - C<host:port,host:port...>, C<id@noderef>, C<id>
65 71
66A noderef is a string that either uniquely identifies a given node (for 72A node reference is a string that either simply identifies the node (for
67private and hidden nodes), or contains a recipe on how to reach a given 73private and slave nodes), or contains a recipe on how to reach a given
68node (for public nodes). 74node (for public nodes).
69 75
76This recipe is simply a comma-separated list of C<address:port> pairs (for
77TCP/IP, other protocols might look different).
78
79Node references come in two flavours: resolved (containing only numerical
80addresses) or unresolved (where hostnames are used instead of addresses).
81
82Before using an unresolved node reference in a message you first have to
83resolve it.
84
70=back 85=back
71 86
72=head1 VARIABLES/FUNCTIONS 87=head1 VARIABLES/FUNCTIONS
73 88
74=over 4 89=over 4
85 100
86use AE (); 101use AE ();
87 102
88use base "Exporter"; 103use base "Exporter";
89 104
90our $VERSION = '0.02'; 105our $VERSION = '0.1';
91our @EXPORT = qw( 106our @EXPORT = qw(
92 NODE $NODE *SELF node_of _any_ 107 NODE $NODE *SELF node_of _any_
93 become_slave become_public 108 resolve_node initialise_node
94 snd rcv mon kil reg psub 109 snd rcv mon kil reg psub
95 port 110 port
96); 111);
97 112
98our $SELF; 113our $SELF;
112 127
113=item $noderef = node_of $portid 128=item $noderef = node_of $portid
114 129
115Extracts and returns the noderef from a portid or a noderef. 130Extracts and returns the noderef from a portid or a noderef.
116 131
132=item $cv = resolve_node $noderef
133
134Takes an unresolved node reference that may contain hostnames and
135abbreviated IDs, resolves all of them and returns a resolved node
136reference.
137
138In addition to C<address:port> pairs allowed in resolved noderefs, the
139following forms are supported:
140
141=over 4
142
143=item the empty string
144
145An empty-string component gets resolved as if the default port (4040) was
146specified.
147
148=item naked port numbers (e.g. C<1234>)
149
150These are resolved by prepending the local nodename and a colon, to be
151further resolved.
152
153=item hostnames (e.g. C<localhost:1234>, C<localhost>)
154
155These are resolved by using AnyEvent::DNS to resolve them, optionally
156looking up SRV records for the C<aemp=4040> port, if no port was
157specified.
158
159=back
160
117=item $SELF 161=item $SELF
118 162
119Contains the current port id while executing C<rcv> callbacks or C<psub> 163Contains the current port id while executing C<rcv> callbacks or C<psub>
120blocks. 164blocks.
121 165
145JSON is used, then only strings, numbers and arrays and hashes consisting 189JSON is used, then only strings, numbers and arrays and hashes consisting
146of those are allowed (no objects). When Storable is used, then anything 190of those are allowed (no objects). When Storable is used, then anything
147that Storable can serialise and deserialise is allowed, and for the local 191that Storable can serialise and deserialise is allowed, and for the local
148node, anything can be passed. 192node, anything can be passed.
149 193
150=item kil $portid[, @reason]
151
152Kill the specified port with the given C<@reason>.
153
154If no C<@reason> is specified, then the port is killed "normally" (linked
155ports will not be kileld, or even notified).
156
157Otherwise, linked ports get killed with the same reason (second form of
158C<mon>, see below).
159
160Runtime errors while evaluating C<rcv> callbacks or inside C<psub> blocks
161will be reported as reason C<< die => $@ >>.
162
163Transport/communication errors are reported as C<< transport_error =>
164$message >>.
165
166=item $guard = mon $portid, $cb->(@reason)
167
168=item $guard = mon $portid, $otherport
169
170=item $guard = mon $portid, $otherport, @msg
171
172Monitor the given port and do something when the port is killed.
173
174In the first form, the callback is simply called with any number
175of C<@reason> elements (no @reason means that the port was deleted
176"normally"). Note also that I<< the callback B<must> never die >>, so use
177C<eval> if unsure.
178
179In the second form, the other port will be C<kil>'ed with C<@reason>, iff
180a @reason was specified, i.e. on "normal" kils nothing happens, while
181under all other conditions, the other port is killed with the same reason.
182
183In the last form, a message of the form C<@msg, @reason> will be C<snd>.
184
185Example: call a given callback when C<$port> is killed.
186
187 mon $port, sub { warn "port died because of <@_>\n" };
188
189Example: kill ourselves when C<$port> is killed abnormally.
190
191 mon $port, $self;
192
193Example: send us a restart message another C<$port> is killed.
194
195 mon $port, $self => "restart";
196
197=cut
198
199sub mon {
200 my ($noderef, $port, $cb) = ((split /#/, shift, 2), shift);
201
202 my $node = $NODE{$noderef} || add_node $noderef;
203
204 #TODO: ports must not be references
205 if (!ref $cb or "AnyEvent::MP::Port" eq ref $cb) {
206 if (@_) {
207 # send a kill info message
208 my (@msg) = ($cb, @_);
209 $cb = sub { snd @msg, @_ };
210 } else {
211 # simply kill other port
212 my $port = $cb;
213 $cb = sub { kil $port, @_ if @_ };
214 }
215 }
216
217 $node->monitor ($port, $cb);
218
219 defined wantarray
220 and AnyEvent::Util::guard { $node->unmonitor ($port, $cb) }
221}
222
223=item $guard = mon_guard $port, $ref, $ref...
224
225Monitors the given C<$port> and keeps the passed references. When the port
226is killed, the references will be freed.
227
228Optionally returns a guard that will stop the monitoring.
229
230This function is useful when you create e.g. timers or other watchers and
231want to free them when the port gets killed:
232
233 $port->rcv (start => sub {
234 my $timer; $timer = mon_guard $port, AE::timer 1, 1, sub {
235 undef $timer if 0.9 < rand;
236 });
237 });
238
239=cut
240
241sub mon_guard {
242 my ($port, @refs) = @_;
243
244 mon $port, sub { 0 && @refs }
245}
246
247=item $local_port = port 194=item $local_port = port
248 195
249Create a new local port object that supports message matching. 196Create a new local port object that can be used either as a pattern
197matching port ("full port") or a single-callback port ("miniport"),
198depending on how C<rcv> callbacks are bound to the object.
250 199
251=item $portid = port { my @msg = @_; $finished } 200=item $portid = port { my @msg = @_; $finished }
252 201
253Creates a "mini port", that is, a very lightweight port without any 202Creates a "mini port", that is, a very lightweight port without any
254pattern matching behind it, and returns its ID. 203pattern matching behind it, and returns its ID.
260The message will be passed as-is, no extra argument (i.e. no port id) will 209The message will be passed as-is, no extra argument (i.e. no port id) will
261be passed to the callback. 210be passed to the callback.
262 211
263If you need the local port id in the callback, this works nicely: 212If you need the local port id in the callback, this works nicely:
264 213
265 my $port; $port = miniport { 214 my $port; $port = port {
266 snd $otherport, reply => $port; 215 snd $otherport, reply => $port;
267 }; 216 };
268 217
269=cut 218=cut
270 219
331 my ($portid, $name) = @_; 280 my ($portid, $name) = @_;
332 281
333 $REG{$name} = $portid; 282 $REG{$name} = $portid;
334} 283}
335 284
285=item rcv $portid, $callback->(@msg)
286
287Replaces the callback on the specified miniport (or newly created port
288object, see C<port>). Full ports are configured with the following calls:
289
336=item rcv $portid, tagstring => $callback->(@msg), ... 290=item rcv $portid, tagstring => $callback->(@msg), ...
337 291
338=item rcv $portid, $smartmatch => $callback->(@msg), ... 292=item rcv $portid, $smartmatch => $callback->(@msg), ...
339 293
340=item rcv $portid, [$smartmatch...] => $callback->(@msg), ... 294=item rcv $portid, [$smartmatch...] => $callback->(@msg), ...
341 295
342Register callbacks to be called on matching messages on the given port. 296Register callbacks to be called on matching messages on the given full
297port (or newly created port).
343 298
344The callback has to return a true value when its work is done, after 299The callback has to return a true value when its work is done, after
345which is will be removed, or a false value in which case it will stay 300which is will be removed, or a false value in which case it will stay
346registered. 301registered.
347 302
363also the most efficient match (by far). 318also the most efficient match (by far).
364 319
365=cut 320=cut
366 321
367sub rcv($@) { 322sub rcv($@) {
323 my $portid = shift;
368 my ($noderef, $port) = split /#/, shift, 2; 324 my ($noderef, $port) = split /#/, $port, 2;
369 325
370 ($NODE{$noderef} || add_node $noderef) == $NODE{""} 326 ($NODE{$noderef} || add_node $noderef) == $NODE{""}
371 or Carp::croak "$noderef#$port: rcv can only be called on local ports, caught"; 327 or Carp::croak "$noderef#$port: rcv can only be called on local ports, caught";
372 328
373 my $self = $PORT_DATA{$port} 329 my $self = $PORT_DATA{$port}
388 : push @{ $self->{rc0}{$match->[0]} }, [$cb]; 344 : push @{ $self->{rc0}{$match->[0]} }, [$cb];
389 } else { 345 } else {
390 push @{ $self->{any} }, [$cb, $match]; 346 push @{ $self->{any} }, [$cb, $match];
391 } 347 }
392 } 348 }
349
350 $portid
393} 351}
394 352
395=item $closure = psub { BLOCK } 353=item $closure = psub { BLOCK }
396 354
397Remembers C<$SELF> and creates a closure out of the BLOCK. When the 355Remembers C<$SELF> and creates a closure out of the BLOCK. When the
428 $res 386 $res
429 } 387 }
430 } 388 }
431} 389}
432 390
391=item $guard = mon $portid, $cb->(@reason)
392
393=item $guard = mon $portid, $otherport
394
395=item $guard = mon $portid, $otherport, @msg
396
397Monitor the given port and do something when the port is killed.
398
399In the first form, the callback is simply called with any number
400of C<@reason> elements (no @reason means that the port was deleted
401"normally"). Note also that I<< the callback B<must> never die >>, so use
402C<eval> if unsure.
403
404In the second form, the other port will be C<kil>'ed with C<@reason>, iff
405a @reason was specified, i.e. on "normal" kils nothing happens, while
406under all other conditions, the other port is killed with the same reason.
407
408In the last form, a message of the form C<@msg, @reason> will be C<snd>.
409
410Example: call a given callback when C<$port> is killed.
411
412 mon $port, sub { warn "port died because of <@_>\n" };
413
414Example: kill ourselves when C<$port> is killed abnormally.
415
416 mon $port, $self;
417
418Example: send us a restart message another C<$port> is killed.
419
420 mon $port, $self => "restart";
421
422=cut
423
424sub mon {
425 my ($noderef, $port) = split /#/, shift, 2;
426
427 my $node = $NODE{$noderef} || add_node $noderef;
428
429 my $cb = shift;
430
431 unless (ref $cb) {
432 if (@_) {
433 # send a kill info message
434 my (@msg) = ($cb, @_);
435 $cb = sub { snd @msg, @_ };
436 } else {
437 # simply kill other port
438 my $port = $cb;
439 $cb = sub { kil $port, @_ if @_ };
440 }
441 }
442
443 $node->monitor ($port, $cb);
444
445 defined wantarray
446 and AnyEvent::Util::guard { $node->unmonitor ($port, $cb) }
447}
448
449=item $guard = mon_guard $port, $ref, $ref...
450
451Monitors the given C<$port> and keeps the passed references. When the port
452is killed, the references will be freed.
453
454Optionally returns a guard that will stop the monitoring.
455
456This function is useful when you create e.g. timers or other watchers and
457want to free them when the port gets killed:
458
459 $port->rcv (start => sub {
460 my $timer; $timer = mon_guard $port, AE::timer 1, 1, sub {
461 undef $timer if 0.9 < rand;
462 });
463 });
464
465=cut
466
467sub mon_guard {
468 my ($port, @refs) = @_;
469
470 mon $port, sub { 0 && @refs }
471}
472
473=item lnk $port1, $port2
474
475Link two ports. This is simply a shorthand for:
476
477 mon $port1, $port2;
478 mon $port2, $port1;
479
480It means that if either one is killed abnormally, the other one gets
481killed as well.
482
483=item kil $portid[, @reason]
484
485Kill the specified port with the given C<@reason>.
486
487If no C<@reason> is specified, then the port is killed "normally" (linked
488ports will not be kileld, or even notified).
489
490Otherwise, linked ports get killed with the same reason (second form of
491C<mon>, see below).
492
493Runtime errors while evaluating C<rcv> callbacks or inside C<psub> blocks
494will be reported as reason C<< die => $@ >>.
495
496Transport/communication errors are reported as C<< transport_error =>
497$message >>.
498
433=back 499=back
434 500
435=head1 FUNCTIONS FOR NODES 501=head1 FUNCTIONS FOR NODES
436 502
437=over 4 503=over 4
438 504
439=item become_public endpoint... 505=item become_public $noderef
440 506
441Tells the node to become a public node, i.e. reachable from other nodes. 507Tells the node to become a public node, i.e. reachable from other nodes.
442 508
443If no arguments are given, or the first argument is C<undef>, then 509The first argument is the (unresolved) node reference of the local node
444AnyEvent::MP tries to bind on port C<4040> on all IP addresses that the 510(if missing then the empty string is used).
445local nodename resolves to.
446 511
447Otherwise the first argument must be an array-reference with transport 512It is quite common to not specify anything, in which case the local node
448endpoints ("ip:port", "hostname:port") or port numbers (in which case the 513tries to listen on the default port, or to only specify a port number, in
449local nodename is used as hostname). The endpoints are all resolved and 514which case AnyEvent::MP tries to guess the local addresses.
450will become the node reference.
451 515
452=cut 516=cut
453 517
454=back 518=back
455 519
458Nodes understand the following messages sent to them. Many of them take 522Nodes understand the following messages sent to them. Many of them take
459arguments called C<@reply>, which will simply be used to compose a reply 523arguments called C<@reply>, which will simply be used to compose a reply
460message - C<$reply[0]> is the port to reply to, C<$reply[1]> the type and 524message - C<$reply[0]> is the port to reply to, C<$reply[1]> the type and
461the remaining arguments are simply the message data. 525the remaining arguments are simply the message data.
462 526
527While other messages exist, they are not public and subject to change.
528
463=over 4 529=over 4
464 530
465=cut 531=cut
466 532
467=item lookup => $name, @reply 533=item lookup => $name, @reply
495 snd $NODE, time => $myport, timereply => 1, 2; 561 snd $NODE, time => $myport, timereply => 1, 2;
496 # => snd $myport, timereply => 1, 2, <time> 562 # => snd $myport, timereply => 1, 2, <time>
497 563
498=back 564=back
499 565
566=head1 AnyEvent::MP vs. Distributed Erlang
567
568AnyEvent::MP got lots of its ideas from distributed erlang (erlang node
569== aemp node, erlang process == aemp port), so many of the documents and
570programming techniques employed by erlang apply to AnyEvent::MP. Here is a
571sample:
572
573 http://www.erlang.se/doc/programming_rules.shtml
574 http://erlang.org/doc/getting_started/part_frame.html # chapters 3 and 4
575 http://erlang.org/download/erlang-book-part1.pdf # chapters 5 and 6
576 http://erlang.org/download/armstrong_thesis_2003.pdf # chapters 4 and 5
577
578Despite the similarities, there are also some important differences:
579
580=over 4
581
582=item * Node references contain the recipe on how to contact them.
583
584Erlang relies on special naming and DNS to work everywhere in the
585same way. AEMP relies on each node knowing it's own address(es), with
586convenience functionality.
587
588This means that AEMP requires a less tightly controlled environment at the
589cost of longer node references and a slightly higher management overhead.
590
591=item * Erlang uses processes and a mailbox, AEMP does not queue.
592
593Erlang uses processes that selctively receive messages, and therefore
594needs a queue. AEMP is event based, queuing messages would serve no useful
595purpose.
596
597(But see L<Coro::MP> for a more erlang-like process model on top of AEMP).
598
599=item * Erlang sends are synchronous, AEMP sends are asynchronous.
600
601Sending messages in erlang is synchronous and blocks the process. AEMP
602sends are immediate, connection establishment is handled in the
603background.
604
605=item * Erlang can silently lose messages, AEMP cannot.
606
607Erlang makes few guarantees on messages delivery - messages can get lost
608without any of the processes realising it (i.e. you send messages a, b,
609and c, and the other side only receives messages a and c).
610
611AEMP guarantees correct ordering, and the guarantee that there are no
612holes in the message sequence.
613
614=item * In erlang, processes can be declared dead and later be found to be
615alive.
616
617In erlang it can happen that a monitored process is declared dead and
618linked processes get killed, but later it turns out that the process is
619still alive - and can receive messages.
620
621In AEMP, when port monitoring detects a port as dead, then that port will
622eventually be killed - it cannot happen that a node detects a port as dead
623and then later sends messages to it, finding it is still alive.
624
625=item * Erlang can send messages to the wrong port, AEMP does not.
626
627In erlang it is quite possible that a node that restarts reuses a process
628ID known to other nodes for a completely different process, causing
629messages destined for that process to end up in an unrelated process.
630
631AEMP never reuses port IDs, so old messages or old port IDs floating
632around in the network will not be sent to an unrelated port.
633
634=item * Erlang uses unprotected connections, AEMP uses secure
635authentication and can use TLS.
636
637AEMP can use a proven protocol - SSL/TLS - to protect connections and
638securely authenticate nodes.
639
640=item * The AEMP protocol is optimised for both text-based and binary
641communications.
642
643The AEMP protocol, unlike the erlang protocol, supports both
644language-independent text-only protocols (good for debugging) and binary,
645language-specific serialisers (e.g. Storable).
646
647It has also been carefully designed to be implementable in other languages
648with a minimum of work while gracefully degrading fucntionality to make the
649protocol simple.
650
651=back
652
500=head1 SEE ALSO 653=head1 SEE ALSO
501 654
502L<AnyEvent>. 655L<AnyEvent>.
503 656
504=head1 AUTHOR 657=head1 AUTHOR

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines