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.91 by root, Tue Sep 22 09:54:42 2009 UTC vs.
Revision 1.126 by root, Sat Mar 3 19:43:41 2012 UTC

30 rcv $port, pong => sub { warn "pong received\n" }; 30 rcv $port, pong => sub { warn "pong received\n" };
31 31
32 # create a port on another node 32 # create a port on another node
33 my $port = spawn $node, $initfunc, @initdata; 33 my $port = spawn $node, $initfunc, @initdata;
34 34
35 # destroy a port again
36 kil $port; # "normal" kill
37 kil $port, my_error => "everything is broken"; # error kill
38
35 # monitoring 39 # monitoring
36 mon $localport, $cb->(@msg) # callback is invoked on death 40 mon $localport, $cb->(@msg) # callback is invoked on death
37 mon $localport, $otherport # kill otherport on abnormal death 41 mon $localport, $otherport # kill otherport on abnormal death
38 mon $localport, $otherport, @msg # send message on death 42 mon $localport, $otherport, @msg # send message on death
43
44 # temporarily execute code in port context
45 peval $port, sub { die "kill the port!" };
46
47 # execute callbacks in $SELF port context
48 my $timer = AE::timer 1, 0, psub {
49 die "kill the port, delayed";
50 };
39 51
40=head1 CURRENT STATUS 52=head1 CURRENT STATUS
41 53
42 bin/aemp - stable. 54 bin/aemp - stable.
43 AnyEvent::MP - stable API, should work. 55 AnyEvent::MP - stable API, should work.
66 78
67Ports allow you to register C<rcv> handlers that can match all or just 79Ports allow you to register C<rcv> handlers that can match all or just
68some messages. Messages send to ports will not be queued, regardless of 80some messages. Messages send to ports will not be queued, regardless of
69anything was listening for them or not. 81anything was listening for them or not.
70 82
83Ports are represented by (printable) strings called "port IDs".
84
71=item port ID - C<nodeid#portname> 85=item port ID - C<nodeid#portname>
72 86
73A port ID is the concatenation of a node ID, a hash-mark (C<#>) as 87A port ID is the concatenation of a node ID, a hash-mark (C<#>)
74separator, and a port name (a printable string of unspecified format). 88as separator, and a port name (a printable string of unspecified
89format created by AnyEvent::MP).
75 90
76=item node 91=item node
77 92
78A node is a single process containing at least one port - the node port, 93A node is a single process containing at least one port - the node port,
79which enables nodes to manage each other remotely, and to create new 94which enables nodes to manage each other remotely, and to create new
80ports. 95ports.
81 96
82Nodes are either public (have one or more listening ports) or private 97Nodes are either public (have one or more listening ports) or private
83(no listening ports). Private nodes cannot talk to other private nodes 98(no listening ports). Private nodes cannot talk to other private nodes
84currently. 99currently, but all nodes can talk to public nodes.
85 100
101Nodes is represented by (printable) strings called "node IDs".
102
86=item node ID - C<[A-Z_][a-zA-Z0-9_\-.:]*> 103=item node ID - C<[A-Za-z0-9_\-.:]*>
87 104
88A node ID is a string that uniquely identifies the node within a 105A node ID is a string that uniquely identifies the node within a
89network. Depending on the configuration used, node IDs can look like a 106network. Depending on the configuration used, node IDs can look like a
90hostname, a hostname and a port, or a random string. AnyEvent::MP itself 107hostname, a hostname and a port, or a random string. AnyEvent::MP itself
91doesn't interpret node IDs in any way. 108doesn't interpret node IDs in any way except to uniquely identify a node.
92 109
93=item binds - C<ip:port> 110=item binds - C<ip:port>
94 111
95Nodes can only talk to each other by creating some kind of connection to 112Nodes can only talk to each other by creating some kind of connection to
96each other. To do this, nodes should listen on one or more local transport 113each other. To do this, nodes should listen on one or more local transport
114endpoints - binds.
115
97endpoints - binds. Currently, only standard C<ip:port> specifications can 116Currently, only standard C<ip:port> specifications can be used, which
98be used, which specify TCP ports to listen on. 117specify TCP ports to listen on. So a bind is basically just a tcp socket
118in listening mode thta accepts conenctions form other nodes.
99 119
100=item seed nodes 120=item seed nodes
101 121
102When a node starts, it knows nothing about the network. To teach the node 122When a node starts, it knows nothing about the network it is in - it
103about the network it first has to contact some other node within the 123needs to connect to at least one other node that is already in the
104network. This node is called a seed. 124network. These other nodes are called "seed nodes".
105 125
106Apart from the fact that other nodes know them as seed nodes and they have 126Seed nodes themselves are not special - they are seed nodes only because
107to have fixed listening addresses, seed nodes are perfectly normal nodes - 127some other node I<uses> them as such, but any node can be used as seed
108any node can function as a seed node for others. 128node for other nodes, and eahc node cna use a different set of seed nodes.
109 129
110In addition to discovering the network, seed nodes are also used to 130In addition to discovering the network, seed nodes are also used to
111maintain the network and to connect nodes that otherwise would have 131maintain the network - all nodes using the same seed node form are part of
112trouble connecting. They form the backbone of an AnyEvent::MP network. 132the same network. If a network is split into multiple subnets because e.g.
133the network link between the parts goes down, then using the same seed
134nodes for all nodes ensures that eventually the subnets get merged again.
113 135
114Seed nodes are expected to be long-running, and at least one seed node 136Seed nodes are expected to be long-running, and at least one seed node
115should always be available. They should also be relatively responsive - a 137should always be available. They should also be relatively responsive - a
116seed node that blocks for long periods will slow down everybody else. 138seed node that blocks for long periods will slow down everybody else.
117 139
140For small networks, it's best if every node uses the same set of seed
141nodes. For large networks, it can be useful to specify "regional" seed
142nodes for most nodes in an area, and use all seed nodes as seed nodes for
143each other. What's important is that all seed nodes connections form a
144complete graph, so that the network cannot split into separate subnets
145forever.
146
147Seed nodes are represented by seed IDs.
148
118=item seeds - C<host:port> 149=item seed IDs - C<host:port>
119 150
120Seeds are transport endpoint(s) (usually a hostname/IP address and a 151Seed IDs are transport endpoint(s) (usually a hostname/IP address and a
121TCP port) of nodes thta should be used as seed nodes. 152TCP port) of nodes that should be used as seed nodes.
122 153
123The nodes listening on those endpoints are expected to be long-running, 154=item global nodes
124and at least one of those should always be available. When nodes run out 155
125of connections (e.g. due to a network error), they try to re-establish 156An AEMP network needs a discovery service - nodes need to know how to
126connections to some seednodes again to join the network. 157connect to other nodes they only know by name. In addition, AEMP offers a
158distributed "group database", which maps group names to a list of strings
159- for example, to register worker ports.
160
161A network needs at least one global node to work, and allows every node to
162be a global node.
163
164Any node that loads the L<AnyEvent::MP::Global> module becomes a global
165node and tries to keep connections to all other nodes. So while it can
166make sense to make every node "global" in small networks, it usually makes
167sense to only make seed nodes into global nodes in large networks (nodes
168keep connections to seed nodes and global nodes, so makign them the same
169reduces overhead).
127 170
128=back 171=back
129 172
130=head1 VARIABLES/FUNCTIONS 173=head1 VARIABLES/FUNCTIONS
131 174
133 176
134=cut 177=cut
135 178
136package AnyEvent::MP; 179package AnyEvent::MP;
137 180
181use AnyEvent::MP::Config ();
138use AnyEvent::MP::Kernel; 182use AnyEvent::MP::Kernel;
183use AnyEvent::MP::Kernel qw(%NODE %PORT %PORT_DATA $UNIQ $RUNIQ $ID);
139 184
140use common::sense; 185use common::sense;
141 186
142use Carp (); 187use Carp ();
143 188
144use AE (); 189use AE ();
190use Guard ();
145 191
146use base "Exporter"; 192use base "Exporter";
147 193
148our $VERSION = $AnyEvent::MP::Kernel::VERSION; 194our $VERSION = $AnyEvent::MP::Config::VERSION;
149 195
150our @EXPORT = qw( 196our @EXPORT = qw(
151 NODE $NODE *SELF node_of after 197 NODE $NODE *SELF node_of after
152 configure 198 configure
153 snd rcv mon mon_guard kil psub spawn cal 199 snd rcv mon mon_guard kil psub peval spawn cal
154 port 200 port
201 db_set db_del db_reg
155); 202);
156 203
157our $SELF; 204our $SELF;
158 205
159sub _self_die() { 206sub _self_die() {
182some other nodes in the network to discover other nodes. 229some other nodes in the network to discover other nodes.
183 230
184This function configures a node - it must be called exactly once (or 231This function configures a node - it must be called exactly once (or
185never) before calling other AnyEvent::MP functions. 232never) before calling other AnyEvent::MP functions.
186 233
234The key/value pairs are basically the same ones as documented for the
235F<aemp> command line utility (sans the set/del prefix), with two additions:
236
237=over 4
238
239=item norc => $boolean (default false)
240
241If true, then the rc file (e.g. F<~/.perl-anyevent-mp>) will I<not>
242be consulted - all configuraiton options must be specified in the
243C<configure> call.
244
245=item force => $boolean (default false)
246
247IF true, then the values specified in the C<configure> will take
248precedence over any values configured via the rc file. The default is for
249the rc file to override any options specified in the program.
250
251=back
252
187=over 4 253=over 4
188 254
189=item step 1, gathering configuration from profiles 255=item step 1, gathering configuration from profiles
190 256
191The function first looks up a profile in the aemp configuration (see the 257The function first looks up a profile in the aemp configuration (see the
204That means that the values specified in the profile have highest priority 270That means that the values specified in the profile have highest priority
205and the values specified directly via C<configure> have lowest priority, 271and the values specified directly via C<configure> have lowest priority,
206and can only be used to specify defaults. 272and can only be used to specify defaults.
207 273
208If the profile specifies a node ID, then this will become the node ID of 274If the profile specifies a node ID, then this will become the node ID of
209this process. If not, then the profile name will be used as node ID. The 275this process. If not, then the profile name will be used as node ID, with
210special node ID of C<anon/> will be replaced by a random node ID. 276a unique randoms tring (C</%u>) appended.
277
278The node ID can contain some C<%> sequences that are expanded: C<%n>
279is expanded to the local nodename, C<%u> is replaced by a random
280strign to make the node unique. For example, the F<aemp> commandline
281utility uses C<aemp/%n/%u> as nodename, which might expand to
282C<aemp/cerebro/ZQDGSIkRhEZQDGSIkRhE>.
211 283
212=item step 2, bind listener sockets 284=item step 2, bind listener sockets
213 285
214The next step is to look up the binds in the profile, followed by binding 286The next step is to look up the binds in the profile, followed by binding
215aemp protocol listeners on all binds specified (it is possible and valid 287aemp protocol listeners on all binds specified (it is possible and valid
221used, meaning the node will bind on a dynamically-assigned port on every 293used, meaning the node will bind on a dynamically-assigned port on every
222local IP address it finds. 294local IP address it finds.
223 295
224=item step 3, connect to seed nodes 296=item step 3, connect to seed nodes
225 297
226As the last step, the seeds list from the profile is passed to the 298As the last step, the seed ID list from the profile is passed to the
227L<AnyEvent::MP::Global> module, which will then use it to keep 299L<AnyEvent::MP::Global> module, which will then use it to keep
228connectivity with at least one node at any point in time. 300connectivity with at least one node at any point in time.
229 301
230=back 302=back
231 303
232Example: become a distributed node using the local node name as profile. 304Example: become a distributed node using the local node name as profile.
233This should be the most common form of invocation for "daemon"-type nodes. 305This should be the most common form of invocation for "daemon"-type nodes.
234 306
235 configure 307 configure
236 308
237Example: become an anonymous node. This form is often used for commandline 309Example: become a semi-anonymous node. This form is often used for
238clients. 310commandline clients.
239 311
240 configure nodeid => "anon/"; 312 configure nodeid => "myscript/%n/%u";
241 313
242Example: configure a node using a profile called seed, which si suitable 314Example: configure a node using a profile called seed, which is suitable
243for a seed node as it binds on all local addresses on a fixed port (4040, 315for a seed node as it binds on all local addresses on a fixed port (4040,
244customary for aemp). 316customary for aemp).
245 317
246 # use the aemp commandline utility 318 # use the aemp commandline utility
247 # aemp profile seed nodeid anon/ binds '*:4040' 319 # aemp profile seed binds '*:4040'
248 320
249 # then use it 321 # then use it
250 configure profile => "seed"; 322 configure profile => "seed";
251 323
252 # or simply use aemp from the shell again: 324 # or simply use aemp from the shell again:
322sub _kilme { 394sub _kilme {
323 die "received message on port without callback"; 395 die "received message on port without callback";
324} 396}
325 397
326sub port(;&) { 398sub port(;&) {
327 my $id = "$UNIQ." . $ID++; 399 my $id = $UNIQ . ++$ID;
328 my $port = "$NODE#$id"; 400 my $port = "$NODE#$id";
329 401
330 rcv $port, shift || \&_kilme; 402 rcv $port, shift || \&_kilme;
331 403
332 $port 404 $port
371 msg1 => sub { ... }, 443 msg1 => sub { ... },
372 ... 444 ...
373 ; 445 ;
374 446
375Example: temporarily register a rcv callback for a tag matching some port 447Example: temporarily register a rcv callback for a tag matching some port
376(e.g. for a rpc reply) and unregister it after a message was received. 448(e.g. for an rpc reply) and unregister it after a message was received.
377 449
378 rcv $port, $otherport => sub { 450 rcv $port, $otherport => sub {
379 my @reply = @_; 451 my @reply = @_;
380 452
381 rcv $SELF, $otherport; 453 rcv $SELF, $otherport;
394 if (ref $_[0]) { 466 if (ref $_[0]) {
395 if (my $self = $PORT_DATA{$portid}) { 467 if (my $self = $PORT_DATA{$portid}) {
396 "AnyEvent::MP::Port" eq ref $self 468 "AnyEvent::MP::Port" eq ref $self
397 or Carp::croak "$port: rcv can only be called on message matching ports, caught"; 469 or Carp::croak "$port: rcv can only be called on message matching ports, caught";
398 470
399 $self->[2] = shift; 471 $self->[0] = shift;
400 } else { 472 } else {
401 my $cb = shift; 473 my $cb = shift;
402 $PORT{$portid} = sub { 474 $PORT{$portid} = sub {
403 local $SELF = $port; 475 local $SELF = $port;
404 eval { &$cb }; _self_die if $@; 476 eval { &$cb }; _self_die if $@;
405 }; 477 };
406 } 478 }
407 } elsif (defined $_[0]) { 479 } elsif (defined $_[0]) {
408 my $self = $PORT_DATA{$portid} ||= do { 480 my $self = $PORT_DATA{$portid} ||= do {
409 my $self = bless [$PORT{$port} || sub { }, { }, $port], "AnyEvent::MP::Port"; 481 my $self = bless [$PORT{$portid} || sub { }, { }, $port], "AnyEvent::MP::Port";
410 482
411 $PORT{$portid} = sub { 483 $PORT{$portid} = sub {
412 local $SELF = $port; 484 local $SELF = $port;
413 485
414 if (my $cb = $self->[1]{$_[0]}) { 486 if (my $cb = $self->[1]{$_[0]}) {
436 } 508 }
437 509
438 $port 510 $port
439} 511}
440 512
513=item peval $port, $coderef[, @args]
514
515Evaluates the given C<$codref> within the contetx of C<$port>, that is,
516when the code throews an exception the C<$port> will be killed.
517
518Any remaining args will be passed to the callback. Any return values will
519be returned to the caller.
520
521This is useful when you temporarily want to execute code in the context of
522a port.
523
524Example: create a port and run some initialisation code in it's context.
525
526 my $port = port { ... };
527
528 peval $port, sub {
529 init
530 or die "unable to init";
531 };
532
533=cut
534
535sub peval($$) {
536 local $SELF = shift;
537 my $cb = shift;
538
539 if (wantarray) {
540 my @res = eval { &$cb };
541 _self_die if $@;
542 @res
543 } else {
544 my $res = eval { &$cb };
545 _self_die if $@;
546 $res
547 }
548}
549
441=item $closure = psub { BLOCK } 550=item $closure = psub { BLOCK }
442 551
443Remembers C<$SELF> and creates a closure out of the BLOCK. When the 552Remembers C<$SELF> and creates a closure out of the BLOCK. When the
444closure is executed, sets up the environment in the same way as in C<rcv> 553closure is executed, sets up the environment in the same way as in C<rcv>
445callbacks, i.e. runtime errors will cause the port to get C<kil>ed. 554callbacks, i.e. runtime errors will cause the port to get C<kil>ed.
555
556The effect is basically as if it returned C<< sub { peval $SELF, sub {
557BLOCK }, @_ } >>.
446 558
447This is useful when you register callbacks from C<rcv> callbacks: 559This is useful when you register callbacks from C<rcv> callbacks:
448 560
449 rcv delayed_reply => sub { 561 rcv delayed_reply => sub {
450 my ($delay, @reply) = @_; 562 my ($delay, @reply) = @_;
523delivered again. 635delivered again.
524 636
525Inter-host-connection timeouts and monitoring depend on the transport 637Inter-host-connection timeouts and monitoring depend on the transport
526used. The only transport currently implemented is TCP, and AnyEvent::MP 638used. The only transport currently implemented is TCP, and AnyEvent::MP
527relies on TCP to detect node-downs (this can take 10-15 minutes on a 639relies on TCP to detect node-downs (this can take 10-15 minutes on a
528non-idle connection, and usually around two hours for idle conenctions). 640non-idle connection, and usually around two hours for idle connections).
529 641
530This means that monitoring is good for program errors and cleaning up 642This means that monitoring is good for program errors and cleaning up
531stuff eventually, but they are no replacement for a timeout when you need 643stuff eventually, but they are no replacement for a timeout when you need
532to ensure some maximum latency. 644to ensure some maximum latency.
533 645
565 } 677 }
566 678
567 $node->monitor ($port, $cb); 679 $node->monitor ($port, $cb);
568 680
569 defined wantarray 681 defined wantarray
570 and AnyEvent::Util::guard { $node->unmonitor ($port, $cb) } 682 and ($cb += 0, Guard::guard { $node->unmonitor ($port, $cb) })
571} 683}
572 684
573=item $guard = mon_guard $port, $ref, $ref... 685=item $guard = mon_guard $port, $ref, $ref...
574 686
575Monitors the given C<$port> and keeps the passed references. When the port 687Monitors the given C<$port> and keeps the passed references. When the port
598 710
599=item kil $port[, @reason] 711=item kil $port[, @reason]
600 712
601Kill the specified port with the given C<@reason>. 713Kill the specified port with the given C<@reason>.
602 714
603If no C<@reason> is specified, then the port is killed "normally" (ports 715If no C<@reason> is specified, then the port is killed "normally" -
604monitoring other ports will not necessarily die because a port dies 716monitor callback will be invoked, but the kil will not cause linked ports
605"normally"). 717(C<mon $mport, $lport> form) to get killed.
606 718
607Otherwise, linked ports get killed with the same reason (second form of 719If a C<@reason> is specified, then linked ports (C<mon $mport, $lport>
608C<mon>, see above). 720form) get killed with the same reason.
609 721
610Runtime errors while evaluating C<rcv> callbacks or inside C<psub> blocks 722Runtime errors while evaluating C<rcv> callbacks or inside C<psub> blocks
611will be reported as reason C<< die => $@ >>. 723will be reported as reason C<< die => $@ >>.
612 724
613Transport/communication errors are reported as C<< transport_error => 725Transport/communication errors are reported as C<< transport_error =>
679} 791}
680 792
681sub spawn(@) { 793sub spawn(@) {
682 my ($nodeid, undef) = split /#/, shift, 2; 794 my ($nodeid, undef) = split /#/, shift, 2;
683 795
684 my $id = "$RUNIQ." . $ID++; 796 my $id = $RUNIQ . ++$ID;
685 797
686 $_[0] =~ /::/ 798 $_[0] =~ /::/
687 or Carp::croak "spawn init function must be a fully-qualified name, caught"; 799 or Carp::croak "spawn init function must be a fully-qualified name, caught";
688 800
689 snd_to_func $nodeid, "AnyEvent::MP::_spawn" => $id, @_; 801 snd_to_func $nodeid, "AnyEvent::MP::_spawn" => $id, @_;
690 802
691 "$nodeid#$id" 803 "$nodeid#$id"
692} 804}
805
693 806
694=item after $timeout, @msg 807=item after $timeout, @msg
695 808
696=item after $timeout, $callback 809=item after $timeout, $callback
697 810
727 840
728If an optional time-out (in seconds) is given and it is not C<undef>, 841If an optional time-out (in seconds) is given and it is not C<undef>,
729then the callback will be called without any arguments after the time-out 842then the callback will be called without any arguments after the time-out
730elapsed and the port is C<kil>ed. 843elapsed and the port is C<kil>ed.
731 844
732If no time-out is given, then the local port will monitor the remote port 845If no time-out is given (or it is C<undef>), then the local port will
733instead, so it eventually gets cleaned-up. 846monitor the remote port instead, so it eventually gets cleaned-up.
734 847
735Currently this function returns the temporary port, but this "feature" 848Currently this function returns the temporary port, but this "feature"
736might go in future versions unless you can make a convincing case that 849might go in future versions unless you can make a convincing case that
737this is indeed useful for something. 850this is indeed useful for something.
738 851
767 $port 880 $port
768} 881}
769 882
770=back 883=back
771 884
885=head1 DISTRIBUTED DATABASE
886
887AnyEvent::MP comes with a simple distributed database. The database will
888be mirrored asynchronously at all global nodes. Other nodes bind to one of
889the global nodes for their needs.
890
891The database consists of a two-level hash - a hash contains a hash which
892contains values.
893
894The top level hash key is called "family", and the second-level hash key
895is called "subkey" or simply "key".
896
897The family must be alphanumeric, i.e. start with a letter and consist
898of letters, digits, underscores and colons (C<[A-Za-z][A-Za-z0-9_:]*>,
899pretty much like Perl module names.
900
901As the family namespace is global, it is recommended to prefix family names
902with the name of the application or module using it.
903
904The subkeys must be non-empty strings, with no further restrictions.
905
906The values should preferably be strings, but other perl scalars should
907work as well (such as undef, arrays and hashes).
908
909Every database entry is owned by one node - adding the same family/subkey
910combination on multiple nodes will not cause discomfort for AnyEvent::MP,
911but the result might be nondeterministic, i.e. the key might have
912different values on different nodes.
913
914Different subkeys in the same family can be owned by different nodes
915without problems, and in fact, this is the common method to create worker
916pools. For example, a worker port for image scaling might do this:
917
918 db_set my_image_scalers => $port;
919
920And clients looking for an image scaler will want to get the
921C<my_image_scalers> keys:
922
923 db_keys "my_image_scalers" => 60 => sub {
924 #d##TODO#
925
926=over
927
928=item db_set $family => $subkey [=> $value]
929
930Sets (or replaces) a key to the database - if C<$value> is omitted,
931C<undef> is used instead.
932
933=item db_del $family => $subkey
934
935Deletes a key from the database.
936
937=item $guard = db_reg $family => $subkey [=> $value]
938
939Sets the key on the database and returns a guard. When the guard is
940destroyed, the key is deleted from the database. If C<$value> is missing,
941then C<undef> is used.
942
943=cut
944
945=back
946
772=head1 AnyEvent::MP vs. Distributed Erlang 947=head1 AnyEvent::MP vs. Distributed Erlang
773 948
774AnyEvent::MP got lots of its ideas from distributed Erlang (Erlang node 949AnyEvent::MP got lots of its ideas from distributed Erlang (Erlang node
775== aemp node, Erlang process == aemp port), so many of the documents and 950== aemp node, Erlang process == aemp port), so many of the documents and
776programming techniques employed by Erlang apply to AnyEvent::MP. Here is a 951programming techniques employed by Erlang apply to AnyEvent::MP. Here is a
777sample: 952sample:
778 953
779 http://www.Erlang.se/doc/programming_rules.shtml 954 http://www.erlang.se/doc/programming_rules.shtml
780 http://Erlang.org/doc/getting_started/part_frame.html # chapters 3 and 4 955 http://erlang.org/doc/getting_started/part_frame.html # chapters 3 and 4
781 http://Erlang.org/download/Erlang-book-part1.pdf # chapters 5 and 6 956 http://erlang.org/download/erlang-book-part1.pdf # chapters 5 and 6
782 http://Erlang.org/download/armstrong_thesis_2003.pdf # chapters 4 and 5 957 http://erlang.org/download/armstrong_thesis_2003.pdf # chapters 4 and 5
783 958
784Despite the similarities, there are also some important differences: 959Despite the similarities, there are also some important differences:
785 960
786=over 4 961=over 4
787 962
788=item * Node IDs are arbitrary strings in AEMP. 963=item * Node IDs are arbitrary strings in AEMP.
789 964
790Erlang relies on special naming and DNS to work everywhere in the same 965Erlang relies on special naming and DNS to work everywhere in the same
791way. AEMP relies on each node somehow knowing its own address(es) (e.g. by 966way. AEMP relies on each node somehow knowing its own address(es) (e.g. by
792configuration or DNS), but will otherwise discover other odes itself. 967configuration or DNS), and possibly the addresses of some seed nodes, but
968will otherwise discover other nodes (and their IDs) itself.
793 969
794=item * Erlang has a "remote ports are like local ports" philosophy, AEMP 970=item * Erlang has a "remote ports are like local ports" philosophy, AEMP
795uses "local ports are like remote ports". 971uses "local ports are like remote ports".
796 972
797The failure modes for local ports are quite different (runtime errors 973The failure modes for local ports are quite different (runtime errors
806ports being the special case/exception, where transport errors cannot 982ports being the special case/exception, where transport errors cannot
807occur. 983occur.
808 984
809=item * Erlang uses processes and a mailbox, AEMP does not queue. 985=item * Erlang uses processes and a mailbox, AEMP does not queue.
810 986
811Erlang uses processes that selectively receive messages, and therefore 987Erlang uses processes that selectively receive messages out of order, and
812needs a queue. AEMP is event based, queuing messages would serve no 988therefore needs a queue. AEMP is event based, queuing messages would serve
813useful purpose. For the same reason the pattern-matching abilities of 989no useful purpose. For the same reason the pattern-matching abilities
814AnyEvent::MP are more limited, as there is little need to be able to 990of AnyEvent::MP are more limited, as there is little need to be able to
815filter messages without dequeuing them. 991filter messages without dequeuing them.
816 992
817(But see L<Coro::MP> for a more Erlang-like process model on top of AEMP). 993This is not a philosophical difference, but simply stems from AnyEvent::MP
994being event-based, while Erlang is process-based.
995
996You cna have a look at L<Coro::MP> for a more Erlang-like process model on
997top of AEMP and Coro threads.
818 998
819=item * Erlang sends are synchronous, AEMP sends are asynchronous. 999=item * Erlang sends are synchronous, AEMP sends are asynchronous.
820 1000
821Sending messages in Erlang is synchronous and blocks the process (and 1001Sending messages in Erlang is synchronous and blocks the process until
1002a conenction has been established and the message sent (and so does not
822so does not need a queue that can overflow). AEMP sends are immediate, 1003need a queue that can overflow). AEMP sends return immediately, connection
823connection establishment is handled in the background. 1004establishment is handled in the background.
824 1005
825=item * Erlang suffers from silent message loss, AEMP does not. 1006=item * Erlang suffers from silent message loss, AEMP does not.
826 1007
827Erlang makes few guarantees on messages delivery - messages can get lost 1008Erlang implements few guarantees on messages delivery - messages can get
828without any of the processes realising it (i.e. you send messages a, b, 1009lost without any of the processes realising it (i.e. you send messages a,
829and c, and the other side only receives messages a and c). 1010b, and c, and the other side only receives messages a and c).
830 1011
831AEMP guarantees correct ordering, and the guarantee that after one message 1012AEMP guarantees (modulo hardware errors) correct ordering, and the
832is lost, all following ones sent to the same port are lost as well, until 1013guarantee that after one message is lost, all following ones sent to the
833monitoring raises an error, so there are no silent "holes" in the message 1014same port are lost as well, until monitoring raises an error, so there are
834sequence. 1015no silent "holes" in the message sequence.
1016
1017If you want your software to be very reliable, you have to cope with
1018corrupted and even out-of-order messages in both Erlang and AEMP. AEMP
1019simply tries to work better in common error cases, such as when a network
1020link goes down.
835 1021
836=item * Erlang can send messages to the wrong port, AEMP does not. 1022=item * Erlang can send messages to the wrong port, AEMP does not.
837 1023
838In Erlang it is quite likely that a node that restarts reuses a process ID 1024In Erlang it is quite likely that a node that restarts reuses an Erlang
839known to other nodes for a completely different process, causing messages 1025process ID known to other nodes for a completely different process,
840destined for that process to end up in an unrelated process. 1026causing messages destined for that process to end up in an unrelated
1027process.
841 1028
842AEMP never reuses port IDs, so old messages or old port IDs floating 1029AEMP does not reuse port IDs, so old messages or old port IDs floating
843around in the network will not be sent to an unrelated port. 1030around in the network will not be sent to an unrelated port.
844 1031
845=item * Erlang uses unprotected connections, AEMP uses secure 1032=item * Erlang uses unprotected connections, AEMP uses secure
846authentication and can use TLS. 1033authentication and can use TLS.
847 1034
850 1037
851=item * The AEMP protocol is optimised for both text-based and binary 1038=item * The AEMP protocol is optimised for both text-based and binary
852communications. 1039communications.
853 1040
854The AEMP protocol, unlike the Erlang protocol, supports both programming 1041The AEMP protocol, unlike the Erlang protocol, supports both programming
855language independent text-only protocols (good for debugging) and binary, 1042language independent text-only protocols (good for debugging), and binary,
856language-specific serialisers (e.g. Storable). By default, unless TLS is 1043language-specific serialisers (e.g. Storable). By default, unless TLS is
857used, the protocol is actually completely text-based. 1044used, the protocol is actually completely text-based.
858 1045
859It has also been carefully designed to be implementable in other languages 1046It has also been carefully designed to be implementable in other languages
860with a minimum of work while gracefully degrading functionality to make the 1047with a minimum of work while gracefully degrading functionality to make the
861protocol simple. 1048protocol simple.
862 1049
863=item * AEMP has more flexible monitoring options than Erlang. 1050=item * AEMP has more flexible monitoring options than Erlang.
864 1051
865In Erlang, you can chose to receive I<all> exit signals as messages 1052In Erlang, you can chose to receive I<all> exit signals as messages or
866or I<none>, there is no in-between, so monitoring single processes is 1053I<none>, there is no in-between, so monitoring single Erlang processes is
867difficult to implement. Monitoring in AEMP is more flexible than in 1054difficult to implement.
868Erlang, as one can choose between automatic kill, exit message or callback 1055
869on a per-process basis. 1056Monitoring in AEMP is more flexible than in Erlang, as one can choose
1057between automatic kill, exit message or callback on a per-port basis.
870 1058
871=item * Erlang tries to hide remote/local connections, AEMP does not. 1059=item * Erlang tries to hide remote/local connections, AEMP does not.
872 1060
873Monitoring in Erlang is not an indicator of process death/crashes, in the 1061Monitoring in Erlang is not an indicator of process death/crashes, in the
874same way as linking is (except linking is unreliable in Erlang). 1062same way as linking is (except linking is unreliable in Erlang).
896overhead, as well as having to keep a proxy object everywhere. 1084overhead, as well as having to keep a proxy object everywhere.
897 1085
898Strings can easily be printed, easily serialised etc. and need no special 1086Strings can easily be printed, easily serialised etc. and need no special
899procedures to be "valid". 1087procedures to be "valid".
900 1088
901And as a result, a miniport consists of a single closure stored in a 1089And as a result, a port with just a default receiver consists of a single
902global hash - it can't become much cheaper. 1090code reference stored in a global hash - it can't become much cheaper.
903 1091
904=item Why favour JSON, why not a real serialising format such as Storable? 1092=item Why favour JSON, why not a real serialising format such as Storable?
905 1093
906In fact, any AnyEvent::MP node will happily accept Storable as framing 1094In fact, any AnyEvent::MP node will happily accept Storable as framing
907format, but currently there is no way to make a node use Storable by 1095format, but currently there is no way to make a node use Storable by
923 1111
924L<AnyEvent::MP::Intro> - a gentle introduction. 1112L<AnyEvent::MP::Intro> - a gentle introduction.
925 1113
926L<AnyEvent::MP::Kernel> - more, lower-level, stuff. 1114L<AnyEvent::MP::Kernel> - more, lower-level, stuff.
927 1115
928L<AnyEvent::MP::Global> - network maintainance and port groups, to find 1116L<AnyEvent::MP::Global> - network maintenance and port groups, to find
929your applications. 1117your applications.
1118
1119L<AnyEvent::MP::DataConn> - establish data connections between nodes.
930 1120
931L<AnyEvent::MP::LogCatcher> - simple service to display log messages from 1121L<AnyEvent::MP::LogCatcher> - simple service to display log messages from
932all nodes. 1122all nodes.
933 1123
934L<AnyEvent>. 1124L<AnyEvent>.

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines