/
Session.pm
1754 lines (1346 loc) · 54.4 KB
/
Session.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package POE::Session;
use strict;
use vars qw($VERSION);
$VERSION = '1.267'; # NOTE - Should be #.### (three decimal places)
use Carp qw(carp croak);
use Errno;
sub SE_NAMESPACE () { 0 }
sub SE_OPTIONS () { 1 }
sub SE_STATES () { 2 }
sub CREATE_ARGS () { 'args' }
sub CREATE_OPTIONS () { 'options' }
sub CREATE_INLINES () { 'inline_states' }
sub CREATE_PACKAGES () { 'package_states' }
sub CREATE_OBJECTS () { 'object_states' }
sub CREATE_HEAP () { 'heap' }
sub OPT_TRACE () { 'trace' }
sub OPT_DEBUG () { 'debug' }
sub OPT_DEFAULT () { 'default' }
sub EN_START () { '_start' }
sub EN_DEFAULT () { '_default' }
sub EN_SIGNAL () { '_signal' }
#------------------------------------------------------------------------------
# Debugging flags for subsystems. They're done as double evals here
# so that someone may define them before using POE::Session (or POE),
# and the pre-defined value will take precedence over the defaults
# here.
# Shorthand for defining an assert constant.
sub _define_assert {
no strict 'refs';
foreach my $name (@_) {
local $^W = 0;
next if defined *{"ASSERT_$name"}{CODE};
if (defined *{"POE::Kernel::ASSERT_$name"}{CODE}) {
eval(
"sub ASSERT_$name () { " .
*{"POE::Kernel::ASSERT_$name"}{CODE}->() .
"}"
);
die if $@;
}
else {
eval "sub ASSERT_$name () { ASSERT_DEFAULT }";
die if $@;
}
}
}
# Shorthand for defining a trace constant.
sub _define_trace {
no strict 'refs';
local $^W = 0;
foreach my $name (@_) {
next if defined *{"TRACE_$name"}{CODE};
if (defined *{"POE::Kernel::TRACE_$name"}{CODE}) {
eval(
"sub TRACE_$name () { " .
*{"POE::Kernel::TRACE_$name"}{CODE}->() .
"}"
);
die if $@;
}
else {
eval "sub TRACE_$name () { TRACE_DEFAULT }";
die if $@;
}
}
}
BEGIN {
# ASSERT_DEFAULT changes the default value for other ASSERT_*
# constants. It inherits POE::Kernel's ASSERT_DEFAULT value, if
# it's present.
unless (defined &ASSERT_DEFAULT) {
if (defined &POE::Kernel::ASSERT_DEFAULT) {
eval( "sub ASSERT_DEFAULT () { " . &POE::Kernel::ASSERT_DEFAULT . " }" );
}
else {
eval 'sub ASSERT_DEFAULT () { 0 }';
}
};
# TRACE_DEFAULT changes the default value for other TRACE_*
# constants. It inherits POE::Kernel's TRACE_DEFAULT value, if
# it's present.
unless (defined &TRACE_DEFAULT) {
if (defined &POE::Kernel::TRACE_DEFAULT) {
eval( "sub TRACE_DEFAULT () { " . &POE::Kernel::TRACE_DEFAULT . " }" );
}
else {
eval 'sub TRACE_DEFAULT () { 0 }';
}
};
_define_assert("STATES");
_define_trace("DESTROY");
}
#------------------------------------------------------------------------------
# Export constants into calling packages. This is evil; perhaps
# EXPORT_OK instead? The parameters NFA has in common with SESSION
# (and other sessions) must be kept at the same offsets as each-other.
sub OBJECT () { 0 } # TODO - deprecate and replace with SELF
sub SESSION () { 1 }
sub KERNEL () { 2 }
sub HEAP () { 3 }
sub STATE () { 4 } # TODO - deprecate and replace with EVENT
sub SENDER () { 5 }
# NFA keeps its state in 6. unused in session so that args match up.
sub CALLER_FILE () { 7 }
sub CALLER_LINE () { 8 }
sub CALLER_STATE () { 9 } # TODO - deprecate and replace with CALLER_EVENT
sub ARG0 () { 10 }
sub ARG1 () { 11 }
sub ARG2 () { 12 }
sub ARG3 () { 13 }
sub ARG4 () { 14 }
sub ARG5 () { 15 }
sub ARG6 () { 16 }
sub ARG7 () { 17 }
sub ARG8 () { 18 }
sub ARG9 () { 19 }
sub import {
my $package = caller();
no strict 'refs';
*{ $package . '::OBJECT' } = \&OBJECT;
*{ $package . '::SESSION' } = \&SESSION;
*{ $package . '::KERNEL' } = \&KERNEL;
*{ $package . '::HEAP' } = \&HEAP;
*{ $package . '::STATE' } = \&STATE;
*{ $package . '::SENDER' } = \&SENDER;
*{ $package . '::ARG0' } = \&ARG0;
*{ $package . '::ARG1' } = \&ARG1;
*{ $package . '::ARG2' } = \&ARG2;
*{ $package . '::ARG3' } = \&ARG3;
*{ $package . '::ARG4' } = \&ARG4;
*{ $package . '::ARG5' } = \&ARG5;
*{ $package . '::ARG6' } = \&ARG6;
*{ $package . '::ARG7' } = \&ARG7;
*{ $package . '::ARG8' } = \&ARG8;
*{ $package . '::ARG9' } = \&ARG9;
*{ $package . '::CALLER_FILE' } = \&CALLER_FILE;
*{ $package . '::CALLER_LINE' } = \&CALLER_LINE;
*{ $package . '::CALLER_STATE' } = \&CALLER_STATE;
}
sub instantiate {
my $type = shift;
croak "$type requires a working Kernel"
unless defined $POE::Kernel::poe_kernel;
my $self =
bless [ { }, # SE_NAMESPACE
{ }, # SE_OPTIONS
{ }, # SE_STATES
], $type;
if (ASSERT_STATES) {
$self->[SE_OPTIONS]->{+OPT_DEFAULT} = 1;
}
return $self;
}
sub try_alloc {
my ($self, @args) = @_;
# Verify that the session has a special start state, otherwise how
# do we know what to do? Don't even bother registering the session
# if the start state doesn't exist.
if (exists $self->[SE_STATES]->{+EN_START}) {
$POE::Kernel::poe_kernel->session_alloc($self, @args);
}
else {
carp( "discarding session ",
$POE::Kernel::poe_kernel->ID_session_to_id($self),
" - no '_start' state"
);
$self = undef;
}
$self;
}
#------------------------------------------------------------------------------
# New style constructor. This uses less DWIM and more DWIS, and it's
# more comfortable for some folks; especially the ones who don't quite
# know WTM.
sub create {
my ($type, @params) = @_;
my @args;
# We treat the parameter list strictly as a hash. Rather than dying
# here with a Perl error, we'll catch it and blame it on the user.
if (@params & 1) {
croak "odd number of events/handlers (missing one or the other?)";
}
my %params = @params;
my $self = $type->instantiate(\%params);
# Process _start arguments. We try to do the right things with what
# we're given. If the arguments are a list reference, map its items
# to ARG0..ARGn; otherwise make whatever the heck it is be ARG0.
if (exists $params{+CREATE_ARGS}) {
if (ref($params{+CREATE_ARGS}) eq 'ARRAY') {
push @args, @{$params{+CREATE_ARGS}};
}
else {
push @args, $params{+CREATE_ARGS};
}
delete $params{+CREATE_ARGS};
}
# Process session options here. Several options may be set.
if (exists $params{+CREATE_OPTIONS}) {
if (ref($params{+CREATE_OPTIONS}) eq 'HASH') {
$self->[SE_OPTIONS] = $params{+CREATE_OPTIONS};
}
else {
croak "options for $type constructor is expected to be a HASH reference";
}
delete $params{+CREATE_OPTIONS};
}
# Get down to the business of defining states.
while (my ($param_name, $param_value) = each %params) {
# Inline states are expected to be state-name/coderef pairs.
if ($param_name eq CREATE_INLINES) {
croak "$param_name does not refer to a hash"
unless (ref($param_value) eq 'HASH');
while (my ($state, $handler) = each(%$param_value)) {
croak "inline state for '$state' needs a CODE reference"
unless (ref($handler) eq 'CODE');
$self->_register_state($state, $handler);
}
}
# Package states are expected to be package-name/list-or-hashref
# pairs. If the second part of the pair is a arrayref, then the
# package methods are expected to be named after the states
# they'll handle. If it's a hashref, then the keys are state
# names and the values are package methods that implement them.
elsif ($param_name eq CREATE_PACKAGES) {
croak "$param_name does not refer to an array"
unless (ref($param_value) eq 'ARRAY');
croak "the array for $param_name has an odd number of elements"
if (@$param_value & 1);
# Copy the parameters so they aren't destroyed.
my @param_value = @$param_value;
while (my ($package, $handlers) = splice(@param_value, 0, 2)) {
# TODO What do we do if the package name has some sort of
# blessing? Do we use the blessed thingy's package, or do we
# maybe complain because the user might have wanted to make
# object states instead?
# An array of handlers. The array's items are passed through
# as both state names and package method names.
if (ref($handlers) eq 'ARRAY') {
foreach my $method (@$handlers) {
$self->_register_state($method, $package, $method);
}
}
# A hash of handlers. Hash keys are state names; values are
# package methods to implement them.
elsif (ref($handlers) eq 'HASH') {
while (my ($state, $method) = each %$handlers) {
$self->_register_state($state, $package, $method);
}
}
else {
croak( "states for package '$package' " .
"need to be a hash or array ref"
);
}
}
}
# Object states are expected to be object-reference/
# list-or-hashref pairs. They must be passed to &create in a list
# reference instead of a hash reference because making object
# references into hash keys loses their blessings.
elsif ($param_name eq CREATE_OBJECTS) {
croak "$param_name does not refer to an array"
unless (ref($param_value) eq 'ARRAY');
croak "the array for $param_name has an odd number of elements"
if (@$param_value & 1);
# Copy the parameters so they aren't destroyed.
my @param_value = @$param_value;
while (@param_value) {
my ($object, $handlers) = splice(@param_value, 0, 2);
# Verify that the object is an object. This may catch simple
# mistakes; or it may be overkill since it already checks that
# $param_value is a arrayref.
carp "'$object' is not an object" unless ref($object);
# An array of handlers. The array's items are passed through
# as both state names and object method names.
if (ref($handlers) eq 'ARRAY') {
foreach my $method (@$handlers) {
$self->_register_state($method, $object, $method);
}
}
# A hash of handlers. Hash keys are state names; values are
# package methods to implement them.
elsif (ref($handlers) eq 'HASH') {
while (my ($state, $method) = each %$handlers) {
$self->_register_state($state, $object, $method);
}
}
else {
croak "states for object '$object' need to be a hash or array ref";
}
}
}
# Import an external heap. This is a convenience, since it
# eliminates the need to connect _start options to heap values.
elsif ($param_name eq CREATE_HEAP) {
$self->[SE_NAMESPACE] = $param_value;
}
else {
croak "unknown $type parameter: $param_name";
}
}
return $self->try_alloc(@args);
}
#------------------------------------------------------------------------------
sub DESTROY {
my $self = shift;
# Session's data structures are destroyed through Perl's usual
# garbage collection. TRACE_DESTROY here just shows what's in the
# session before the destruction finishes.
TRACE_DESTROY and do {
require Data::Dumper;
POE::Kernel::_warn(
"----- Session $self Leak Check -----\n",
"-- Namespace (HEAP):\n",
Data::Dumper::Dumper($self->[SE_NAMESPACE]),
"-- Options:\n",
);
foreach (sort keys (%{$self->[SE_OPTIONS]})) {
POE::Kernel::_warn(" $_ = ", $self->[SE_OPTIONS]->{$_}, "\n");
}
POE::Kernel::_warn("-- States:\n");
foreach (sort keys (%{$self->[SE_STATES]})) {
POE::Kernel::_warn(" $_ = ", $self->[SE_STATES]->{$_}, "\n");
}
};
}
#------------------------------------------------------------------------------
sub _invoke_state {
my ($self, $source_session, $state, $etc, $file, $line, $fromstate) = @_;
# Trace the state invocation if tracing is enabled.
if ($self->[SE_OPTIONS]->{+OPT_TRACE}) {
POE::Kernel::_warn(
$POE::Kernel::poe_kernel->ID_session_to_id($self),
" -> $state (from $file at $line)\n"
);
}
# The desired destination state doesn't exist in this session.
# Attempt to redirect the state transition to _default.
unless (exists $self->[SE_STATES]->{$state}) {
# There's no _default either; redirection's not happening today.
# Drop the state transition event on the floor, and optionally
# make some noise about it.
unless (exists $self->[SE_STATES]->{+EN_DEFAULT}) {
$! = exists &Errno::ENOSYS ? &Errno::ENOSYS : &Errno::EIO;
if ($self->[SE_OPTIONS]->{+OPT_DEFAULT} and $state ne EN_SIGNAL) {
my $loggable_self =
$POE::Kernel::poe_kernel->_data_alias_loggable($self);
POE::Kernel::_warn(
"a '$state' event was sent from $file at $line to $loggable_self ",
"but $loggable_self has neither a handler for it ",
"nor one for _default\n"
);
}
return undef;
}
# If we get this far, then there's a _default state to redirect
# the transition to. Trace the redirection.
if ($self->[SE_OPTIONS]->{+OPT_TRACE}) {
POE::Kernel::_warn(
$POE::Kernel::poe_kernel->ID_session_to_id($self),
" -> $state redirected to _default\n"
);
}
# Transmogrify the original state transition into a corresponding
# _default invocation. ARG1 is copied from $etc so it can't be
# altered from a distance.
$etc = [ $state, [@$etc] ];
$state = EN_DEFAULT;
}
# If we get this far, then the state can be invoked. So invoke it
# already!
# Inline states are invoked this way.
if (ref($self->[SE_STATES]->{$state}) eq 'CODE') {
return $self->[SE_STATES]->{$state}->
( undef, # object
$self, # session
$POE::Kernel::poe_kernel, # kernel
$self->[SE_NAMESPACE], # heap
$state, # state
$source_session, # sender
undef, # unused #6
$file, # caller file name
$line, # caller file line
$fromstate, # caller state
@$etc # args
);
}
# Package and object states are invoked this way.
my ($object, $method) = @{$self->[SE_STATES]->{$state}};
return
$object->$method # package/object (implied)
( $self, # session
$POE::Kernel::poe_kernel, # kernel
$self->[SE_NAMESPACE], # heap
$state, # state
$source_session, # sender
undef, # unused #6
$file, # caller file name
$line, # caller file line
$fromstate, # caller state
@$etc # args
);
}
#------------------------------------------------------------------------------
# Add, remove or replace states in the session.
sub _register_state {
my ($self, $name, $handler, $method) = @_;
$method = $name unless defined $method;
# Deprecate _signal.
# RC 2004-09-07 - Decided to leave this in because it blames
# problems with _signal on the user for using it. It should
# probably go away after a little while, but not during the other
# deprecations.
if ($name eq EN_SIGNAL) {
# Report the problem outside POE.
my $caller_level = 0;
local $Carp::CarpLevel = 1;
while ( (caller $caller_level)[0] =~ /^POE::/ ) {
$caller_level++;
$Carp::CarpLevel++;
}
croak(
",----- DEPRECATION ERROR -----\n",
"| The _signal event is deprecated. Please use sig() to register\n",
"| an explicit signal handler instead.\n",
"`-----------------------------\n",
);
}
# There is a handler, so try to define the state. This replaces an
# existing state.
if ($handler) {
# Coderef handlers are inline states.
if (ref($handler) eq 'CODE') {
carp( "redefining handler for event($name) for session(",
$POE::Kernel::poe_kernel->ID_session_to_id($self), ")"
)
if ( $self->[SE_OPTIONS]->{+OPT_DEBUG} &&
(exists $self->[SE_STATES]->{$name})
);
$self->[SE_STATES]->{$name} = $handler;
}
# Non-coderef handlers may be package or object states. See if
# the method belongs to the handler.
elsif ($handler->can($method)) {
carp( "redefining handler for event($name) for session(",
$POE::Kernel::poe_kernel->ID_session_to_id($self), ")"
)
if ( $self->[SE_OPTIONS]->{+OPT_DEBUG} &&
(exists $self->[SE_STATES]->{$name})
);
$self->[SE_STATES]->{$name} = [ $handler, $method ];
}
# Something's wrong. This code also seems wrong, since
# ref($handler) can't be 'CODE'.
else {
if ( (ref($handler) eq 'CODE') and
$self->[SE_OPTIONS]->{+OPT_TRACE}
) {
carp( $POE::Kernel::poe_kernel->ID_session_to_id($self),
" : handler for event($name) is not a proper ref - not registered"
)
}
else {
unless ($handler->can($method)) {
if (length ref($handler)) {
croak "object $handler does not have a '$method' method"
}
else {
croak "package $handler does not have a '$method' method";
}
}
}
}
}
# No handler. Delete the state!
else {
delete $self->[SE_STATES]->{$name};
}
}
#------------------------------------------------------------------------------
# Return the session's ID. This is a thunk into POE::Kernel, where
# the session ID really lies.
sub ID {
$POE::Kernel::poe_kernel->ID_session_to_id(shift);
}
#------------------------------------------------------------------------------
# Set or fetch session options.
sub option {
my $self = shift;
my %return_values;
# Options are set in pairs.
while (@_ >= 2) {
my ($flag, $value) = splice(@_, 0, 2);
$flag = lc($flag);
# If the value is defined, then set the option.
if (defined $value) {
# Change some handy values into boolean representations. This
# clobbers the user's original values for the sake of DWIM-ism.
($value = 1) if ($value =~ /^(on|yes|true)$/i);
($value = 0) if ($value =~ /^(no|off|false)$/i);
$return_values{$flag} = $self->[SE_OPTIONS]->{$flag};
$self->[SE_OPTIONS]->{$flag} = $value;
}
# Remove the option if the value is undefined.
else {
$return_values{$flag} = delete $self->[SE_OPTIONS]->{$flag};
}
}
# If only one option is left, then there's no value to set, so we
# fetch its value.
if (@_) {
my $flag = lc(shift);
$return_values{$flag} =
( exists($self->[SE_OPTIONS]->{$flag})
? $self->[SE_OPTIONS]->{$flag}
: undef
);
}
# If only one option was set or fetched, then return it as a scalar.
# Otherwise return it as a hash of option names and values.
my @return_keys = keys(%return_values);
if (@return_keys == 1) {
return $return_values{$return_keys[0]};
}
else {
return \%return_values;
}
}
# Fetch the session's heap. In rare cases, libraries may need to
# break encapsulation this way, probably also using
# $kernel->get_current_session as an accessory to the crime.
sub get_heap {
my $self = shift;
return $self->[SE_NAMESPACE];
}
#------------------------------------------------------------------------------
# Create an anonymous sub that, when called, posts an event back to a
# session. This maps postback references (stringified; blessing, and
# thus refcount, removed) to parent session IDs. Members are set when
# postbacks are created, and postbacks' DESTROY methods use it to
# perform the necessary cleanup when they go away. Thanks to njt for
# steering me right on this one.
my %anonevent_parent_id;
my %anonevent_weakened;
# I assume that when the postback owner loses all reference to it,
# they are done posting things back to us. That's when the postback's
# DESTROY is triggered, and referential integrity is maintained.
sub POE::Session::AnonEvent::DESTROY {
my $self = shift;
my $parent_id = delete $anonevent_parent_id{$self};
unless (delete $anonevent_weakened{$self}) {
$POE::Kernel::poe_kernel->refcount_decrement( $parent_id, 'anon_event' );
}
}
sub POE::Session::AnonEvent::weaken {
my $self = shift;
unless ($anonevent_weakened{$self}) {
my $parent_id = $anonevent_parent_id{$self};
$POE::Kernel::poe_kernel->refcount_decrement( $parent_id, 'anon_event' );
$anonevent_weakened{$self} = 1;
}
return $self;
}
# Tune postbacks depending on variations in toolkit behavior.
BEGIN {
# Tk blesses its callbacks internally, so we need to wrap our
# blessed callbacks in unblessed ones. Otherwise our postback's
# DESTROY method probably won't be called.
if (exists $INC{'Tk.pm'}) {
eval 'sub USING_TK () { 1 }';
}
else {
eval 'sub USING_TK () { 0 }';
}
};
# Create a postback closure, maintaining referential integrity in the
# process. The next step is to give it to something that expects to
# be handed a callback.
sub postback {
my ($self, $event, @etc) = @_;
my $id = $POE::Kernel::poe_kernel->ID_session_to_id($self);
my $postback = bless sub {
$POE::Kernel::poe_kernel->post( $id, $event, [ @etc ], [ @_ ] );
return 0;
}, 'POE::Session::AnonEvent';
$anonevent_parent_id{$postback} = $id;
$POE::Kernel::poe_kernel->refcount_increment( $id, 'anon_event' );
# Tk blesses its callbacks, so we must present one that isn't
# blessed. Otherwise Tk's blessing would divert our DESTROY call to
# its own, and that's not right.
return sub { $postback->(@_) } if USING_TK;
return $postback;
}
# Create a synchronous callback closure. The return value will be
# passed to whatever is handed the callback.
sub callback {
my ($self, $event, @etc) = @_;
my $id = $POE::Kernel::poe_kernel->ID_session_to_id($self);
my $callback = bless sub {
$POE::Kernel::poe_kernel->call( $id, $event, [ @etc ], [ @_ ] );
}, 'POE::Session::AnonEvent';
$anonevent_parent_id{$callback} = $id;
$POE::Kernel::poe_kernel->refcount_increment( $id, 'anon_event' );
# Tk blesses its callbacks, so we must present one that isn't
# blessed. Otherwise Tk's blessing would divert our DESTROY call to
# its own, and that's not right.
return sub { $callback->(@_) } if USING_TK;
return $callback;
}
1;
__END__
=head1 NAME
POE::Session - a generic event-driven task
=head1 SYNOPSIS
use POE; # auto-includes POE::Kernel and POE::Session
POE::Session->create(
inline_states => {
_start => sub { $_[KERNEL]->yield("next") },
next => sub {
print "tick...\n";
$_[KERNEL]->delay(next => 1);
},
},
);
POE::Kernel->run();
exit;
POE::Session can also dispatch to object and class methods through
L</object_states> and L</package_states> callbacks.
=head1 DESCRIPTION
POE::Session and its subclasses translate events from POE::Kernel's
generic dispatcher into the particular calling conventions suitable for
application code. In design pattern parlance, POE::Session classes
are adapters between L<POE::Kernel> and application code.
The L<sessions|POE::Kernel/Sessions> that POE::Kernel manages are more
like generic task structures. Unfortunately these two disparate
concepts have virtually identical names.
=head2 A note on nomenclature
This documentation will refer to event handlers as "states" in certain
unavoidable situations. Sessions were originally meant to be
event-driven state machines, but their purposes evolved over time.
Some of the legacy vocabulary lives on in the API for backward
compatibility, however.
Confusingly, L<POE::NFA> is a class for implementing actual
event-driven state machines. Its documentation uses "state" in the
proper sense.
=head1 USING POE::Session
POE::Session has two main purposes. First, it maps event names to the
code that will handle them. Second, it maps a consistent event
dispatch interface to those handlers.
Consider the L</SYNOPSIS> for example. A POE::Session instance is
created with two C<inline_states>, each mapping an event name
("_start" and "next") to an inline subroutine. POE::Session ensures
that C<$_[KERNEL]> and so on are meaningful within an event handler.
Event handlers may also be object or class methods, using
L</object_states> and L</package_states> respectively. The create()
syntax is different than for C<inline_states>, but the calling
convention is nearly identical.
Notice that the created POE::Session object has not been saved to a
variable. The new POE::Session object gives itself to POE::Kernel,
which then manages it and all the resources it uses.
It's possible to keep references to new POE::Session objects, but it's
not usually necessary. If an application is not careful about
cleaning up these references you will create circular references,
which will leak memory when POE::Kernel would normally destroy
the POE::Session object. It is recommended that you keep
the session's C</ID> instead.
=head2 POE::Session's Calling Convention
The biggest syntactical hurdle most people have with POE is
POE::Session's unconventional calling convention. For example:
sub handle_event {
my ($kernel, $heap, $parameter) = @_[KERNEL, HEAP, ARG0];
...;
}
Or the use of CL</$_[KERNEL]>, CL</$_[HEAP]> and CL</$_[ARG0]> inline, as is done
in most examples.
What's going on here is rather basic. Perl passes parameters into
subroutines or methods using the @_ array. C<KERNEL>, C<HEAP>, C<ARG0> and
others are constants exported by POE::Session (which is included for
free when a program uses POE).
So CL</$_[KERNEL]> is an event handler's KERNELth parameter. C<@_[HEAP,
ARG0]> is a slice of @_ containing the HEAPth and ARG0th parameters.
While this looks odd, it's perfectly plain and legal Perl syntax. POE
uses it for a few reasons:
=over 4
=item 1
In the common case, passing parameters in C<@_> is faster than passing
hash or array references and then dereferencing them in the handler.
=item 2
Typos in hash-based parameter lists are either subtle runtime
errors or requires constant runtime checking. Constants are either
known at compile time, or are clear compile-time errors.
=item 3
Referencing C<@_> offsets by constants allows parameters to move
in the future without breaking application code.
=item 4
Most event handlers don't need all of C<@_>. Slices allow handlers to
use only the parameters they're interested in.
=back
=head2 POE::Session Parameters
Event handlers receive most of their runtime context in up to nine
callback parameters. POE::Kernel provides many of them.
=head3 $_[OBJECT]
C<$_[OBJECT]> is $self for event handlers that are an object method. It is
the class (package) name for class-based event handlers. It is undef
for plain coderef callbacks, which have no special C<$self>-ish value.
C<OBJECT> is always zero, since C<$_[0]> is always C<$self> or C<$class>
in object and class methods. Coderef handlers are called with
an C<undef> placeholder in C<$_[0]> so that the other offsets remain valid.
It's often useful for method-based event handlers to call other
methods in the same object. C<$_[OBJECT]> helps this happen.
sub ui_update_everything {
my $self = $_[OBJECT];
$self->update_menu();
$self->update_main_window();
$self->update_status_line();
}
You may also use method inheritance
sub Amethod {
my $self = shift;
$self->SUPER::Amethod( @_ );
# ... more work ...
}
=head3 $_[SESSION]
C<$_[SESSION]> is a reference to the current session object. This lets event
handlers access their session's methods. Programs may also compare
C<$_[SESSION]> to CL</$_[SENDER]> to verify that intra-session events did not
come from other sessions.
C<$_[SESSION]> may also be used as the destination for intra-session
CL<post()|POE::Kernel/post> and CL<call()|POE::Kernel/call>. CL<yield()|POE::Kernel/yield> is marginally more convenient and
efficient than C<post($_[SESSION], ...)> however.
It is bad form to access another session directly. The recommended
approach is to manipulate a session through an event handler.
sub enable_trace {
my $previous_trace = $_[SESSION]->option( trace => 1 );
my $id = $_[SESSION]->ID;
if ($previous_trace) {
print "Session $id: dispatch trace is still on.\n";
}
else {
print "Session $id: dispatch trace has been enabled.\n";
}
}
=head3 $_[KERNEL]
The KERNELth parameter is always a reference to the application's
singleton L<POE::Kernel> instance. It is most often used to call
POE::Kernel methods from event handlers.
# Set a 10-second timer.
$_[KERNEL]->delay( time_is_up => 10 );
=head3 $_[HEAP]
Every POE::Session object contains its own variable namespace known as
the session's C<HEAP>. It is modeled and named after process memory
heaps (not priority heaps). Heaps are by default anonymous hash
references, but they may be initialized in L<create()|/create> to be almost
anything. POE::Session itself never uses C<$_[HEAP]>, although some POE
components do.
Heaps do not overlap between sessions, although create()'s "heap"
parameter can be used to make this happen.
These two handlers time the lifespan of a session:
sub _start_handler {
$_[HEAP]{ts_start} = time();
}
sub _stop_handler {
my $time_elapsed = time() - $_[HEAP]{ts_start};
print "Session ", $_[SESSION]->ID, " elapsed seconds: $elapsed\n";
}
=head3 $_[STATE]
The STATEth handler parameter contains the name of the event being
dispatched in the current callback. This can be important since the
event and handler names may significantly differ. Also, a single
handler may be assigned to more than one event.
POE::Session->create(
inline_states => {
one => \&some_handler,
two => \&some_handler,
six => \&some_handler,
ten => \&some_handler,
_start => sub {
$_[KERNEL]->yield($_) for qw(one two six ten);
}
}
);
sub some_handler {
print(
"Session ", $_[SESSION]->ID,
": some_handler() handled event $_[STATE]\n"
);
}
It should be noted however that having event names and handlers names match
will make your code easier to navigate.