--- AnyEvent-MP/MP.pm 2009/08/02 18:11:48 1.12 +++ AnyEvent-MP/MP.pm 2009/08/03 22:05:55 1.20 @@ -86,7 +86,7 @@ our $VERSION = '0.02'; our @EXPORT = qw( - NODE $NODE $PORT snd rcv _any_ + NODE $NODE $PORT snd rcv mon del _any_ create_port create_port_on create_miniport become_slave become_public @@ -120,6 +120,28 @@ that Storable can serialise and deserialise is allowed, and for the local node, anything can be passed. +=item $guard = mon $portid, $cb->() + +Monitor the given port and call the given callback when the port is +destroyed or connection to it's node is lost. + +#TODO + +=cut + +sub mon { + my ($noderef, $port) = split /#/, shift, 2; + + my $node = AnyEvent::MP::Base::add_node $noderef; + + my $cb = shift; + + $node->monitor ($port, $cb); + + defined wantarray + and AnyEvent::Util::guard { $node->unmonitor ($port, $cb) } +} + =item $local_port = create_port Create a new local port object. See the next section for allowed methods. @@ -127,7 +149,7 @@ =cut sub create_port { - my $id = "$AnyEvent::MP::Base::UNIQ." . ++$AnyEvent::MP::Base::ID; + my $id = "$AnyEvent::MP::Base::UNIQ." . $AnyEvent::MP::Base::ID++; my $self = bless { id => "$NODE#$id", @@ -158,20 +180,33 @@ $self } -=item $portid = create_miniport { } +=item $portid = miniport { my @msg = @_; $finished } + +Creates a "mini port", that is, a very lightweight port without any +pattern matching behind it, and returns its ID. + +The block will be called for every message received on the port. When the +callback returns a true value its job is considered "done" and the port +will be destroyed. Otherwise it will stay alive. + +The message will be passed as-is, no extra argument (i.e. no port id) will +be passed to the callback. -Creates a "mini port", that is, a port without much #TODO +If you need the local port id in the callback, this works nicely: + + my $port; $port = miniport { + snd $otherport, reply => $port; + }; =cut -sub create_miniport(&) { +sub miniport(&) { my $cb = shift; - my $id = "$AnyEvent::MP::Base::UNIQ." . ++$AnyEvent::MP::Base::ID; + my $id = "$AnyEvent::MP::Base::UNIQ." . $AnyEvent::MP::Base::ID++; $AnyEvent::MP::Base::PORT{$id} = sub { - $_[0] = "$NODE#$id"; &$cb - and delete $AnyEvent::MP::Base::PORT{$id}; + and del $id; }; "$NODE#$id" @@ -196,6 +231,8 @@ '""' => sub { $_[0]{id} }, fallback => 1; +sub TO_JSON { $_[0]{id} } + =item $port->rcv (type => $callback->($port, @msg)) =item $port->rcv ($smartmatch => $callback->($port, @msg)) @@ -264,6 +301,8 @@ sub destroy { my ($self) = @_; + AnyEvent::MP::Base::del $self->{id}; + delete $AnyEvent::MP::Base::WKP{ $self->{wkname} }; delete $AnyEvent::MP::Base::PORT{$_}