| 1 |
# $Id: TimeoutSocket.pm,v 1.2 2005/02/02 20:44:35 msergeant Exp $ |
| 2 |
|
| 3 |
package Danga::TimeoutSocket; |
| 4 |
|
| 5 |
use base 'Danga::Socket'; |
| 6 |
use fields qw(alive_time create_time); |
| 7 |
|
| 8 |
our $last_cleanup = 0; |
| 9 |
|
| 10 |
Danga::Socket->AddTimer(15, \&_do_cleanup); |
| 11 |
|
| 12 |
sub new { |
| 13 |
my Danga::TimeoutSocket $self = shift; |
| 14 |
my $sock = shift; |
| 15 |
$self = fields::new($self) unless ref($self); |
| 16 |
$self->SUPER::new($sock); |
| 17 |
|
| 18 |
my $now = time; |
| 19 |
$self->{alive_time} = $self->{create_time} = $now; |
| 20 |
|
| 21 |
return $self; |
| 22 |
} |
| 23 |
|
| 24 |
# overload these in a subclass |
| 25 |
sub max_idle_time { 0 } |
| 26 |
sub max_connect_time { 0 } |
| 27 |
|
| 28 |
sub Reset { |
| 29 |
Danga::Socket->Reset; |
| 30 |
Danga::Socket->AddTimer(15, \&_do_cleanup); |
| 31 |
} |
| 32 |
|
| 33 |
sub _do_cleanup { |
| 34 |
my $now = time; |
| 35 |
|
| 36 |
Danga::Socket->AddTimer(15, \&_do_cleanup); |
| 37 |
|
| 38 |
my $sf = __PACKAGE__->get_sock_ref; |
| 39 |
|
| 40 |
my %max_age; # classname -> max age (0 means forever) |
| 41 |
my %max_connect; # classname -> max connect time |
| 42 |
my @to_close; |
| 43 |
while (my $k = each %$sf) { |
| 44 |
my Danga::TimeoutSocket $v = $sf->{$k}; |
| 45 |
my $ref = ref $v; |
| 46 |
next unless $v->isa('Danga::TimeoutSocket'); |
| 47 |
unless (defined $max_age{$ref}) { |
| 48 |
$max_age{$ref} = $ref->max_idle_time || 0; |
| 49 |
$max_connect{$ref} = $ref->max_connect_time || 0; |
| 50 |
} |
| 51 |
if (my $t = $max_connect{$ref}) { |
| 52 |
if ($v->{create_time} < $now - $t) { |
| 53 |
push @to_close, $v; |
| 54 |
next; |
| 55 |
} |
| 56 |
} |
| 57 |
if (my $t = $max_age{$ref}) { |
| 58 |
if ($v->{alive_time} < $now - $t) { |
| 59 |
push @to_close, $v; |
| 60 |
} |
| 61 |
} |
| 62 |
} |
| 63 |
|
| 64 |
$_->close("Timeout") foreach @to_close; |
| 65 |
} |
| 66 |
|
| 67 |
1; |