PrePAN

Sign in to PrePAN

Net::Object::Peer "Network" with pub/sub + direct peer-to-peer messaging

Good

Synopsis

use 5.10.0;

package Node;
use Moo;
with 'Net::Object::Peer';

has name => is => ( 'ro', required => 1 );

sub _notify_subscribed {
    my ( $self, $peer, $name ) = @_;
    say $self->name, ":\t@{[ $peer->name ]} subscribed to event $name";
}

sub _cb_hey {
    my ( $self, $event ) = @_;
    say $self->name, ":\t@{[ $event->emitter->name ]} sent @{[$event->name]}";
}

sub _cb_unsubscribe {
    my ( $self, $event ) = @_;
    say $self->name, ":\t@{[ $event->emitter->name ]} unsubscribed";
}

package main;


my $n1 = Node->new( name => 'N1' );
my $n2 = Node->new( name => 'N2' );
my $n3 = Node->new( name => 'N3' );

# Net::Object::Peer provides an "unsubscribe" event; $n1 will be
# notified when $n2 unsubscribes from it
$n1->subscribe( $n2, 'unsubscribe' );

# $n2 and $n3 will be notified when $n1 sends a "hey" event, and $n1
# will be notified that they have subscribed

$n2->subscribe( $n1, 'hey' );
$n3->subscribe( $n1, 'hey' );

# both $n2 and $n3 will get notified
$n1->emit( 'hey' );

# only $n2 gets notified
$n1->send( $n2, 'hey' );

# destroy $n2; $n2 will unsubscribe from all of its events and $n1
# will be notified that $n2 has unsubscribed from it.
undef $n2;

Description

Net::Object::Peer is a Moo Role which implements a publish/subscribe peer-to-peer messaging system, based upon Beam::Emitter. Objects in the network may broadcast events to all subscribers or may send events to a particular subscriber.

Subscriptions and unsubscriptions are tracked and messages will be sent to affected objects upon request.

While Net::Object::Peer is designed around the concept of nodes being objects with methods as event handlers, it retains Beam::Emitter's ability to register code references as well.

Net::Object::Peer::Cookbook provides some recipes.

I'm not terribly enamored of the module name; suggestions for alternatives would be welcome!

Comments

Please sign up to post a review.