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.8 by root, Sun Aug 2 14:44:37 2009 UTC vs.
Revision 1.22 by root, Tue Aug 4 18:33:30 2009 UTC

4 4
5=head1 SYNOPSIS 5=head1 SYNOPSIS
6 6
7 use AnyEvent::MP; 7 use AnyEvent::MP;
8 8
9 NODE # returns this node identifier
10 $NODE # contains this node identifier 9 $NODE # contains this node's noderef
10 NODE # returns this node's noderef
11 NODE $port # returns the noderef of the port
11 12
12 snd $port, type => data...; 13 snd $port, type => data...;
14
15 $SELF # receiving/own port id in rcv callbacks
13 16
14 rcv $port, smartmatch => $cb->($port, @msg); 17 rcv $port, smartmatch => $cb->($port, @msg);
15 18
16 # examples: 19 # examples:
17 rcv $port2, ping => sub { snd $_[0], "pong"; 0 }; 20 rcv $port2, ping => sub { snd $_[0], "pong"; 0 };
28 31
29Despite its simplicity, you can securely message other processes running 32Despite its simplicity, you can securely message other processes running
30on the same or other hosts. 33on the same or other hosts.
31 34
32At the moment, this module family is severly brokena nd underdocumented, 35At the moment, this module family is severly brokena nd underdocumented,
33so do not use. This was uploaded mainly to resreve the CPAN namespace - 36so do not use. This was uploaded mainly to reserve the CPAN namespace -
34stay tuned! 37stay tuned!
35 38
36=head1 CONCEPTS 39=head1 CONCEPTS
37 40
38=over 4 41=over 4
82 85
83use AE (); 86use AE ();
84 87
85use base "Exporter"; 88use base "Exporter";
86 89
87our $VERSION = '0.01'; 90our $VERSION = '0.02';
88our @EXPORT = qw( 91our @EXPORT = qw(
89 NODE $NODE $PORT snd rcv _any_ 92 NODE $NODE *SELF node_of _any_
90 create_port create_port_on
91 become_slave become_public 93 become_slave become_public
94 snd rcv mon kil reg psub
95 port
92); 96);
93 97
98our $SELF;
99
100sub _self_die() {
101 my $msg = $@;
102 $msg =~ s/\n+$// unless ref $msg;
103 kil $SELF, die => $msg;
104}
105
94=item NODE / $NODE 106=item $thisnode = NODE / $NODE
95 107
96The C<NODE ()> function and the C<$NODE> variable contain the noderef of 108The C<NODE> function returns, and the C<$NODE> variable contains
97the local node. The value is initialised by a call to C<become_public> or 109the noderef of the local node. The value is initialised by a call
98C<become_slave>, after which all local port identifiers become invalid. 110to C<become_public> or C<become_slave>, after which all local port
111identifiers become invalid.
112
113=item $noderef = node_of $portid
114
115Extracts and returns the noderef from a portid or a noderef.
116
117=item $SELF
118
119Contains the current port id while executing C<rcv> callbacks or C<psub>
120blocks.
121
122=item SELF, %SELF, @SELF...
123
124Due to some quirks in how perl exports variables, it is impossible to
125just export C<$SELF>, all the symbols called C<SELF> are exported by this
126module, but only C<$SELF> is currently used.
99 127
100=item snd $portid, type => @data 128=item snd $portid, type => @data
101 129
102=item snd $portid, @msg 130=item snd $portid, @msg
103 131
117JSON is used, then only strings, numbers and arrays and hashes consisting 145JSON is used, then only strings, numbers and arrays and hashes consisting
118of those are allowed (no objects). When Storable is used, then anything 146of those are allowed (no objects). When Storable is used, then anything
119that Storable can serialise and deserialise is allowed, and for the local 147that Storable can serialise and deserialise is allowed, and for the local
120node, anything can be passed. 148node, anything can be passed.
121 149
122=item $local_port = create_port 150=item kil $portid[, @reason]
123 151
124Create a new local port object. See the next section for allowed methods. 152Kill the specified port with the given C<@reason>.
125 153
126=cut 154If no C<@reason> is specified, then the port is killed "normally" (linked
155ports will not be kileld, or even notified).
127 156
128sub create_port { 157Otherwise, linked ports get killed with the same reason (second form of
129 my $id = "$AnyEvent::MP::Base::UNIQ." . ++$AnyEvent::MP::Base::ID; 158C<mon>, see below).
130 159
131 my $self = bless { 160Runtime errors while evaluating C<rcv> callbacks or inside C<psub> blocks
132 id => "$NODE#$id", 161will be reported as reason C<< die => $@ >>.
133 names => [$id],
134 }, "AnyEvent::MP::Port";
135 162
136 $AnyEvent::MP::Base::PORT{$id} = sub { 163Transport/communication errors are reported as C<< transport_error =>
137 unshift @_, $self; 164$message >>.
138 165
139 for (@{ $self->{rc0}{$_[1]} }) { 166=item $guard = mon $portid, $cb->(@reason)
140 $_ && &{$_->[0]} 167
141 && undef $_; 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 @_ };
142 } 214 }
215 }
143 216
144 for (@{ $self->{rcv}{$_[1]} }) { 217 $node->monitor ($port, $cb);
145 $_ && [@_[1 .. @{$_->[1]}]] ~~ $_->[1] 218
146 && &{$_->[0]} 219 defined wantarray
147 && undef $_; 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;
148 } 236 });
237 });
149 238
150 for (@{ $self->{any} }) { 239=cut
151 $_ && [@_[0 .. $#{$_->[1]}]] ~~ $_->[1] 240
152 && &{$_->[0]} 241sub mon_guard {
153 && undef $_; 242 my ($port, @refs) = @_;
154 } 243
244 mon $port, sub { 0 && @refs }
245}
246
247=item $local_port = port
248
249Create a new local port object that supports message matching.
250
251=item $portid = port { my @msg = @_; $finished }
252
253Creates a "mini port", that is, a very lightweight port without any
254pattern matching behind it, and returns its ID.
255
256The block will be called for every message received on the port. When the
257callback returns a true value its job is considered "done" and the port
258will be destroyed. Otherwise it will stay alive.
259
260The message will be passed as-is, no extra argument (i.e. no port id) will
261be passed to the callback.
262
263If you need the local port id in the callback, this works nicely:
264
265 my $port; $port = miniport {
266 snd $otherport, reply => $port;
155 }; 267 };
156 268
157 $self
158}
159
160package AnyEvent::MP::Port;
161
162=back
163
164=head1 METHODS FOR PORT OBJECTS
165
166=over 4
167
168=item "$port"
169
170A port object stringifies to its port ID, so can be used directly for
171C<snd> operations.
172
173=cut 269=cut
174 270
175use overload 271sub port(;&) {
176 '""' => sub { $_[0]{id} }, 272 my $id = "$UNIQ." . $ID++;
177 fallback => 1; 273 my $port = "$NODE#$id";
178 274
179=item $port->rcv (type => $callback->($port, @msg)) 275 if (@_) {
276 my $cb = shift;
277 $PORT{$id} = sub {
278 local $SELF = $port;
279 eval {
280 &$cb
281 and kil $id;
282 };
283 _self_die if $@;
284 };
285 } else {
286 my $self = bless {
287 id => "$NODE#$id",
288 }, "AnyEvent::MP::Port";
180 289
181=item $port->rcv ($smartmatch => $callback->($port, @msg)) 290 $PORT_DATA{$id} = $self;
291 $PORT{$id} = sub {
292 local $SELF = $port;
182 293
294 eval {
295 for (@{ $self->{rc0}{$_[0]} }) {
296 $_ && &{$_->[0]}
297 && undef $_;
298 }
299
300 for (@{ $self->{rcv}{$_[0]} }) {
301 $_ && [@_[1 .. @{$_->[1]}]] ~~ $_->[1]
302 && &{$_->[0]}
303 && undef $_;
304 }
305
306 for (@{ $self->{any} }) {
307 $_ && [@_[0 .. $#{$_->[1]}]] ~~ $_->[1]
308 && &{$_->[0]}
309 && undef $_;
310 }
311 };
312 _self_die if $@;
313 };
314 }
315
316 $port
317}
318
319=item reg $portid, $name
320
321Registers the given port under the name C<$name>. If the name already
322exists it is replaced.
323
324A port can only be registered under one well known name.
325
326A port automatically becomes unregistered when it is killed.
327
328=cut
329
330sub reg(@) {
331 my ($portid, $name) = @_;
332
333 $REG{$name} = $portid;
334}
335
336=item rcv $portid, tagstring => $callback->(@msg), ...
337
338=item rcv $portid, $smartmatch => $callback->(@msg), ...
339
183=item $port->rcv ([$smartmatch...] => $callback->($port, @msg)) 340=item rcv $portid, [$smartmatch...] => $callback->(@msg), ...
184 341
185Register a callback on the given port. 342Register callbacks to be called on matching messages on the given port.
186 343
187The callback has to return a true value when its work is done, after 344The callback has to return a true value when its work is done, after
188which is will be removed, or a false value in which case it will stay 345which is will be removed, or a false value in which case it will stay
189registered. 346registered.
190 347
348The global C<$SELF> (exported by this module) contains C<$portid> while
349executing the callback.
350
351Runtime errors wdurign callback execution will result in the port being
352C<kil>ed.
353
191If the match is an array reference, then it will be matched against the 354If the match is an array reference, then it will be matched against the
192first elements of the message, otherwise only the first element is being 355first elements of the message, otherwise only the first element is being
193matched. 356matched.
194 357
195Any element in the match that is specified as C<_any_> (a function 358Any element in the match that is specified as C<_any_> (a function
200also the most efficient match (by far). 363also the most efficient match (by far).
201 364
202=cut 365=cut
203 366
204sub rcv($@) { 367sub rcv($@) {
205 my ($self, $match, $cb) = @_; 368 my ($noderef, $port) = split /#/, shift, 2;
206 369
370 ($NODE{$noderef} || add_node $noderef) == $NODE{""}
371 or Carp::croak "$noderef#$port: rcv can only be called on local ports, caught";
372
373 my $self = $PORT_DATA{$port}
374 or Carp::croak "$noderef#$port: rcv can only be called on message matching ports, caught";
375
376 "AnyEvent::MP::Port" eq ref $self
377 or Carp::croak "$noderef#$port: rcv can only be called on message matching ports, caught";
378
379 while (@_) {
380 my ($match, $cb) = splice @_, 0, 2;
381
207 if (!ref $match) { 382 if (!ref $match) {
208 push @{ $self->{rc0}{$match} }, [$cb]; 383 push @{ $self->{rc0}{$match} }, [$cb];
209 } elsif (("ARRAY" eq ref $match && !ref $match->[0])) { 384 } elsif (("ARRAY" eq ref $match && !ref $match->[0])) {
210 my ($type, @match) = @$match; 385 my ($type, @match) = @$match;
211 @match 386 @match
212 ? push @{ $self->{rcv}{$match->[0]} }, [$cb, \@match] 387 ? push @{ $self->{rcv}{$match->[0]} }, [$cb, \@match]
213 : push @{ $self->{rc0}{$match->[0]} }, [$cb]; 388 : push @{ $self->{rc0}{$match->[0]} }, [$cb];
214 } else { 389 } else {
215 push @{ $self->{any} }, [$cb, $match]; 390 push @{ $self->{any} }, [$cb, $match];
391 }
216 } 392 }
217} 393}
218 394
219=item $port->register ($name) 395=item $closure = psub { BLOCK }
220 396
221Registers the given port under the well known name C<$name>. If the name 397Remembers C<$SELF> and creates a closure out of the BLOCK. When the
222already exists it is replaced. 398closure is executed, sets up the environment in the same way as in C<rcv>
399callbacks, i.e. runtime errors will cause the port to get C<kil>ed.
223 400
224A port can only be registered under one well known name. 401This is useful when you register callbacks from C<rcv> callbacks:
225 402
226=cut 403 rcv delayed_reply => sub {
404 my ($delay, @reply) = @_;
405 my $timer = AE::timer $delay, 0, psub {
406 snd @reply, $SELF;
407 };
408 };
227 409
228sub register {
229 my ($self, $name) = @_;
230
231 $self->{wkname} = $name;
232 $AnyEvent::MP::Base::WKP{$name} = "$self";
233}
234
235=item $port->destroy
236
237Explicitly destroy/remove/nuke/vaporise the port.
238
239Ports are normally kept alive by there mere existance alone, and need to
240be destroyed explicitly.
241
242=cut 410=cut
243 411
244sub destroy { 412sub psub(&) {
245 my ($self) = @_; 413 my $cb = shift;
246 414
247 delete $AnyEvent::MP::Base::WKP{ $self->{wkname} }; 415 my $port = $SELF
416 or Carp::croak "psub can only be called from within rcv or psub callbacks, not";
248 417
249 delete $AnyEvent::MP::Base::PORT{$_} 418 sub {
250 for @{ $self->{names} }; 419 local $SELF = $port;
420
421 if (wantarray) {
422 my @res = eval { &$cb };
423 _self_die if $@;
424 @res
425 } else {
426 my $res = eval { &$cb };
427 _self_die if $@;
428 $res
429 }
430 }
251} 431}
252 432
253=back 433=back
254 434
255=head1 FUNCTIONS FOR NODES 435=head1 FUNCTIONS FOR NODES
256 436
257=over 4 437=over 4
258
259=item mon $noderef, $callback->($noderef, $status, $)
260
261Monitors the given noderef.
262 438
263=item become_public endpoint... 439=item become_public endpoint...
264 440
265Tells the node to become a public node, i.e. reachable from other nodes. 441Tells the node to become a public node, i.e. reachable from other nodes.
266 442
286 462
287=over 4 463=over 4
288 464
289=cut 465=cut
290 466
291=item wkp => $name, @reply 467=item lookup => $name, @reply
292 468
293Replies with the port ID of the specified well-known port, or C<undef>. 469Replies with the port ID of the specified well-known port, or C<undef>.
294 470
295=item devnull => ... 471=item devnull => ...
296 472

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines