Acme-Parataxis
view release on metacpan or search on metacpan
lib/Acme/Parataxis/Actor.pod view on Meta::CPAN
=pod
=encoding utf8
=head1 NAME
Acme::Parataxis::Actor - A Fiber with a Mailbox
=head1 SYNOPSIS
use v5.40;
use Acme::Parataxis qw[async];
use Acme::Parataxis::Actor;
async {
my $upper = Acme::Parataxis::Actor->spawn( sub ( $self, $msg ) {
return uc $msg->{text};
} );
# ask: queue a message and get a future for the handler's answer
say $upper->ask( { text => 'hello' } )->await; # HELLO
# send: queue a message, expect no answer
$upper->send( { text => 'nobody is reading this' } );
# handle what is queued, then shutdown gracefully
$upper->stop;
};
=head1 DESCRIPTION
An actor is a private fiber with an incoming mailbox. C<spawn> starts one, binds it to a handler, and returns
immediately. The handler runs inside the actor's private fiber, processing one message at a time. Because messages are
serialized and isolated to this single fiber, internal state requires no mutexes or locking: keep your variables inside
the closure and interact with them purely via messages.
Two verbs do the talking:
=over
=item * C<ask( $msg )> queues a message and returns an L<Acme::Parataxis::Future> that resolves with the handler's return value.
=item * C<send( $msg )> queues a message and returns immediately without waiting for an answer.
=back
The handler is invoked as C<< sub ( $self, $msg ) { ... } >>. It may perform any standard cooperative actionâcalling
C<await_sleep>, reading from channels, awaiting other actors, or acquiring locksâand the actor will wait for it to
return before taking the next message.
The mailbox is a bounded L<Acme::Parataxis::Channel>. If producers send messages faster than the handler can process
them, the mailbox fills and subsequent senders park. Because this is a standard fiber wait, round-trips can be bounded
with L<with_timeout|Acme::Parataxis/with_timeout> or cancellation tokens.
Actors can be registered globally by name, hot-swapped while running (C<swap>), and supervised under
L<Acme::Parataxis::Supervisor>.
=head1 METHODS
=head2 C<spawn( $code, [$capacity = 16], [%opts] )>
my $actor = Acme::Parataxis::Actor->spawn(
sub ( $self, $msg ) { ... },
32,
supervised => 1,
name => 'worker'
);
Class factory that spawns and starts a new actor. The handler receives C<($self, $msg)>.
=over
=item * C<$capacity>
Mailbox queue capacity before C<send> and C<ask> park the caller (default 16). Must be C<E<gt>= 1>.
=item * C<supervised =E<gt> 1>
If true, an uncaught exception in the handler terminates the actor so a supervisor can observe the failure and restart
it. If false, an exception only fails that specific message's C<ask> and the actor continues running.
=item * C<name =E<gt> $name>
Registers the actor in the process-wide name table so it can be retrieved via C<< Acme::Parataxis->actor($name) >>.
Must be unique among live actors.
=back
=head2 C<ask( $msg )>
my $future = $actor->ask( { cmd => 'status' } );
my $reply = $future->await;
Enqueues C<$msg> and returns an L<Acme::Parataxis::Future>. If the mailbox is full, the calling fiber parks until space
is available. When the handler finishes, the future resolves with its return value. If the handler dies, the future
fails with that error.
=head2 C<send( $msg )>
$actor->send( { event => 'ping' } );
Enqueues C<$msg> without waiting for a reply. Parks if the mailbox is full. Returns true once queued.
=head2 C<stop( )>
$actor->stop;
Queues a graceful shutdown sentinel behind all currently pending messages. The actor continues processing queued work
and exits once the mailbox drains. From the moment C<stop> is called, new C<ask> or C<send> calls croak. Idempotent.
=head2 C<is_alive( )>
Returns true if the actor's fiber is running or draining; returns false once teardown has completed.
=head2 C<on_death( sub ($actor, $error) { ... } )>
$actor->on_death( sub ( $actor, $err ) {
warn "Actor died: $err" if $err;
} );
Registers a callback that fires once when the actor terminates. C<$error> contains the exception that killed the actor,
or C<undef> if it stopped cleanly. If the actor is already dead, the callback runs immediately.
=head2 C<swap( sub ($self, $msg) { ... } )>
$actor->swap( sub ( $self, $msg ) { ... } );
Atomically replaces the message handler for subsequent messages. The swap takes effect at the next message boundary;
any message currently being executed finishes under the previous handler.
=head2 C<respawn( )>
my $clone = $actor->respawn;
Spawns a fresh actor with the same handler, mailbox capacity, and options. The new actor receives an empty mailbox; any
unanswered requests on the old actor fail on the old actor. Used by supervisors to restart crashed workers.
=head2 C<name( )>
Returns the registered name string, or C<undef> if unnamed.
=head2 C<error( )>
Returns the exception that terminated the actor, or C<undef> if still running or stopped cleanly.
=head2 C<fid( )>
Returns the fiber ID of the actor's message-processing loop.
=head1 THE NAME REGISTRY
=head2 C<< Acme::Parataxis->actor( $name ) >> / C<< Acme::Parataxis->whereis( $name ) >>
my $srv = Acme::Parataxis->actor('logger');
Looks up a live actor registered with C<name =E<gt> $name>. Returns the actor object or C<undef>. Registering an actor
holds a strong reference to it, keeping it alive until explicitly stopped even if all external lexical references are
dropped.
=head1 Recipes
=head2 State encapsulation without locks
my $counter = Acme::Parataxis::Actor->spawn( sub ( $self, $msg ) {
state $count = 0;
if ( $msg eq 'inc' ) { return ++$count }
elsif ( $msg eq 'get' ) { return $count }
} );
$counter->send('inc');
say $counter->ask('get')->await; # 1
=head2 Awaiting complete shutdown
C<stop()> queues a shutdown, but returns immediately. To wait for queued messages to completely drain:
use Acme::Parataxis::Monitor;
$actor->stop;
Acme::Parataxis::Monitor->new( target => $actor )->await;
say 'Actor has completely finished draining';
=head1 Behavior Notes
=over
=item * Failure isolation
On an unsupervised actor (the default), an exception inside the handler fails the corresponding C<ask> future (or
prints a warning if sent via C<send>), but the actor remains alive to handle subsequent messages. Under C<supervised
=E<gt> 1>, a handler die terminates the actor, unregisters its name, fails all pending queued asks, and notifies
supervisors.
=item * Deadlock avoidance
An actor cannot C<ask> itself. Awaiting its own response deadlocks the actor's single message loop. Use C<send> for
( run in 0.925 second using v1.01-cache-2.11-cpan-234fa220139 )