use strict;
use bytes;
use POSIX ();
-use Time::HiRes ();
use IO::Handle qw();
use Fcntl qw(FD_CLOEXEC F_SETFD F_GETFD);
-
+use Time::HiRes qw(clock_gettime CLOCK_MONOTONIC);
+use parent qw(Exporter);
+our @EXPORT_OK = qw(now);
use warnings;
use PublicInbox::Syscall qw(:epoll);
use fields ('sock', # underlying socket
- 'fd', # numeric file descriptor
- 'write_buf', # arrayref of scalars, scalarrefs, or coderefs to write
- 'write_buf_offset', # offset into first array of write_buf to start writing at
- 'write_buf_size', # total length of data in all write_buf items
- 'write_set_watch', # bool: true if we internally set watch_write rather than by a subclass
- 'closed', # bool: socket is closed
+ 'wbuf', # arrayref of scalars, scalarrefs, or coderefs to write
+ 'wbuf_off', # offset into first element of wbuf to start writing at
'event_watch', # bitmask of events the client is interested in (POLLIN,OUT,etc.)
);
-use Errno qw(EINPROGRESS EWOULDBLOCK EISCONN ENOTSOCK
- EPIPE EAGAIN EBADF ECONNRESET ENOPROTOOPT);
+use Errno qw(EAGAIN EINVAL);
use Carp qw(croak confess);
-use constant DebugLevel => 0;
-
use constant POLLIN => 1;
use constant POLLOUT => 4;
use constant POLLERR => 8;
@ToClose, # sockets to close when event loop is done
$PostLoopCallback, # subref to call at the end of each loop, if defined (global)
- %PLCMap, # fd (num) -> PostLoopCallback (per-object)
$LoopTimeout, # timeout of event loop in milliseconds
$DoneInit, # if we've done the one-time module init yet
@Timers = ();
$PostLoopCallback = undef;
- %PLCMap = ();
$DoneInit = 0;
# NOTE kqueue is close-on-fork, and we don't account for it, yet
return $LoopTimeout = $_[1] + 0;
}
-=head2 C<< CLASS->DebugMsg( $format, @args ) >>
-
-Print the debugging message specified by the C<sprintf>-style I<format> and
-I<args>
-
-=cut
-sub DebugMsg {
- my ( $class, $fmt, @args ) = @_;
- chomp $fmt;
- printf STDERR ">>> $fmt\n", @args;
-}
-
=head2 C<< CLASS->AddTimer( $seconds, $coderef ) >>
Add a timer to occur $seconds from now. $seconds may be fractional, but timers
=cut
sub AddTimer {
- my $class = shift;
- my ($secs, $coderef) = @_;
+ my ($class, $secs, $coderef) = @_;
+
+ if (!$secs) {
+ my $timer = bless([0, $coderef], 'PublicInbox::DS::Timer');
+ unshift(@Timers, $timer);
+ return $timer;
+ }
- my $fire_time = Time::HiRes::time() + $secs;
+ my $fire_time = now() + $secs;
my $timer = bless [$fire_time, $coderef], "PublicInbox::DS::Timer";
}
}
+sub now () { clock_gettime(CLOCK_MONOTONIC) }
+
# runs timers and returns milliseconds for next one, or next event loop
sub RunTimers {
return $LoopTimeout unless @Timers;
- my $now = Time::HiRes::time();
+ my $now = now();
# Run expired timers
while (@Timers && $Timers[0][0] <= $now) {
# get up to 1000 events
my $evcount = epoll_wait($Epoll, 1000, $timeout, \@events);
- EVENT:
for ($i=0; $i<$evcount; $i++) {
- my $ev = $events[$i];
-
# it's possible epoll_wait returned many events, including some at the end
# that ones in the front triggered unregister-interest actions. if we
# can't find the %sock entry, it's because we're no longer interested
# in that event.
- my PublicInbox::DS $pob = $DescriptorMap{$ev->[0]};
- my $code;
- my $state = $ev->[1];
-
- DebugLevel >= 1 && $class->DebugMsg("Event: fd=%d (%s), state=%d \@ %s\n",
- $ev->[0], ref($pob), $ev->[1], time);
-
- # standard non-profiling codepat
- $pob->event_read if $state & EPOLLIN && ! $pob->{closed};
- $pob->event_write if $state & EPOLLOUT && ! $pob->{closed};
- if ($state & (EPOLLERR|EPOLLHUP)) {
- $pob->event_err if $state & EPOLLERR && ! $pob->{closed};
- $pob->event_hup if $state & EPOLLHUP && ! $pob->{closed};
- }
+ $DescriptorMap{$events[$i]->[0]}->event_step;
}
return unless PostEventLoop();
}
# Fetch handles with read events
while (@poll) {
my ($fd, $state) = splice(@poll, 0, 2);
- next unless $state;
-
- $pob = $DescriptorMap{$fd};
-
- $pob->event_read if $state & POLLIN && ! $pob->{closed};
- $pob->event_write if $state & POLLOUT && ! $pob->{closed};
- $pob->event_err if $state & POLLERR && ! $pob->{closed};
- $pob->event_hup if $state & POLLHUP && ! $pob->{closed};
+ $DescriptorMap{$fd}->event_step if $state;
}
return unless PostEventLoop();
}
foreach my $kev (@ret) {
- my ($fd, $filter, $flags, $fflags) = @$kev;
- my PublicInbox::DS $pob = $DescriptorMap{$fd};
-
- DebugLevel >= 1 && $class->DebugMsg("Event: fd=%d (%s), flags=%d \@ %s\n",
- $fd, ref($pob), $flags, time);
-
- $pob->event_read if $filter == IO::KQueue::EVFILT_READ() && !$pob->{closed};
- $pob->event_write if $filter == IO::KQueue::EVFILT_WRITE() && !$pob->{closed};
- if ($flags == IO::KQueue::EV_EOF() && !$pob->{closed}) {
- if ($fflags) {
- $pob->event_err;
- } else {
- $pob->event_hup;
- }
- }
+ $DescriptorMap{$kev->[0]}->event_step;
}
return unless PostEventLoop();
}
sub SetPostLoopCallback {
my ($class, $ref) = @_;
- if (ref $class) {
- # per-object callback
- my PublicInbox::DS $self = $class;
- if (defined $ref && ref $ref eq 'CODE') {
- $PLCMap{$self->{fd}} = $ref;
- } else {
- delete $PLCMap{$self->{fd}};
- }
- } else {
- # global callback
- $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
- }
+ # global callback
+ $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
}
# Internal function: run the post-event callback, send read events
$sock->close;
# and now we can finally remove the fd from the map. see
- # comment above in _cleanup.
+ # comment above in ->close.
delete $DescriptorMap{$fd};
}
# or global) cancels it
my $keep_running = 1;
- # per-object post-loop-callbacks
- for my $plc (values %PLCMap) {
- $keep_running &&= $plc->(\%DescriptorMap);
- }
-
# now we're at the very end, call callback if defined
if (defined $PostLoopCallback) {
$keep_running &&= $PostLoopCallback->(\%DescriptorMap);
my ($self, $sock, $exclusive) = @_;
$self = fields::new($self) unless ref $self;
- $self->{sock} = $sock;
+ $self->{sock} = $sock;
my $fd = fileno($sock);
Carp::cluck("undef sock and/or fd in PublicInbox::DS->new. sock=" . ($sock || "") . ", fd=" . ($fd || ""))
unless $sock && $fd;
- $self->{fd} = $fd;
- $self->{write_buf} = [];
- $self->{write_buf_offset} = 0;
- $self->{write_buf_size} = 0;
- $self->{closed} = 0;
+ $self->{wbuf} = [];
my $ev = $self->{event_watch} = POLLERR|POLLHUP|POLLNVAL;
}
retry:
if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
- if ($!{EINVAL} && ($ev & $EPOLLEXCLUSIVE)) {
+ if ($! == EINVAL && ($ev & $EPOLLEXCLUSIVE)) {
$EPOLLEXCLUSIVE = 0; # old kernel
$ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP;
goto retry;
### I N S T A N C E M E T H O D S
#####################################################################
-=head2 C<< $obj->steal_socket() >>
-
-Basically returns our socket and makes it so that we don't try to close it,
-but we do remove it from epoll handlers. THIS CLOSES $self. It is the same
-thing as calling close, except it gives you the socket to use.
-
-=cut
-sub steal_socket {
- my PublicInbox::DS $self = $_[0];
- return if $self->{closed};
-
- # cleanup does most of the work of closing this socket
- $self->_cleanup();
+=head2 C<< $obj->close >>
- # now undef our internal sock and fd structures so we don't use them
- my $sock = $self->{sock};
- $self->{sock} = undef;
- return $sock;
-}
-
-=head2 C<< $obj->close( [$reason] ) >>
-
-Close the socket. The I<reason> argument will be used in debugging messages.
+Close the socket.
=cut
sub close {
- my PublicInbox::DS $self = $_[0];
- return if $self->{closed};
-
- # print out debugging info for this close
- if (DebugLevel) {
- my ($pkg, $filename, $line) = caller;
- my $reason = $_[1] || "";
- warn "Closing \#$self->{fd} due to $pkg/$filename/$line ($reason)\n";
- }
-
- # this does most of the work of closing us
- $self->_cleanup();
-
- # defer closing the actual socket until the event loop is done
- # processing this round of events. (otherwise we might reuse fds)
- if ($self->{sock}) {
- push @ToClose, $self->{sock};
- $self->{sock} = undef;
- }
-
- return 0;
-}
-
-### METHOD: _cleanup()
-### Called by our closers so we can clean internal data structures.
-sub _cleanup {
- my PublicInbox::DS $self = $_[0];
-
- # we're effectively closed; we have no fd and sock when we leave here
- $self->{closed} = 1;
+ my ($self) = @_;
+ my $sock = delete $self->{sock} or return;
# we need to flush our write buffer, as there may
# be self-referential closures (sub { $client->close })
# preventing the object from being destroyed
- $self->{write_buf} = [];
+ @{$self->{wbuf}} = ();
# if we're using epoll, we have to remove this from our epoll fd so we stop getting
# notifications about it
- if ($HaveEpoll && $self->{fd}) {
- if (epoll_ctl($Epoll, EPOLL_CTL_DEL, $self->{fd}, $self->{event_watch}) != 0) {
- # dump_error prints a backtrace so we can try to figure out why this happened
- $self->dump_error("epoll_ctl(): failure deleting fd=$self->{fd} during _cleanup(); $! (" . ($!+0) . ")");
- }
+ if ($HaveEpoll) {
+ my $fd = fileno($sock);
+ epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, $self->{event_watch}) and
+ confess("EPOLL_CTL_DEL: $!");
}
- # now delete from mappings. this fd no longer belongs to us, so we don't want
- # to get alerts for it if it becomes writable/readable/etc.
- delete $PLCMap{$self->{fd}};
-
# we explicitly don't delete from DescriptorMap here until we
# actually close the socket, as we might be in the middle of
# processing an epoll_wait/etc that returned hundreds of fds, one
# of which is not yet processed and is what we're closing. if we
# keep it in DescriptorMap, then the event harnesses can just
- # looked at $pob->{closed} and ignore it. but if it's an
+ # looked at $pob->{sock} == undef and ignore it. but if it's an
# un-accounted for fd, then it (understandably) freak out a bit
# and emit warnings, thinking their state got off.
- # and finally get rid of our fd so we can't use it anywhere else
- $self->{fd} = undef;
-}
-
-=head2 C<< $obj->sock() >>
-
-Returns the underlying IO::Handle for the object.
+ # defer closing the actual socket until the event loop is done
+ # processing this round of events. (otherwise we might reuse fds)
+ push @ToClose, $sock;
-=cut
-sub sock {
- my PublicInbox::DS $self = shift;
- return $self->{sock};
+ return 0;
}
=head2 C<< $obj->write( $data ) >>
# now-dead object does its second write. that is this case. we
# just lie and say it worked. it'll be dead soon and won't be
# hurt by this lie.
- return 1 if $self->{closed};
+ my $sock = $self->{sock} or return 1;
my $bref;
# just queue data if there's already a wait
my $need_queue;
+ my $wbuf = $self->{wbuf};
if (defined $data) {
$bref = ref $data ? $data : \$data;
- if ($self->{write_buf_size}) {
- push @{$self->{write_buf}}, $bref;
- $self->{write_buf_size} += ref $bref eq "SCALAR" ? length($$bref) : 1;
+ if (scalar @$wbuf) {
+ push @$wbuf, $bref;
return 0;
}
WRITE:
while (1) {
- return 1 unless $bref ||= $self->{write_buf}[0];
+ return 1 unless $bref ||= $wbuf->[0];
my $len;
eval {
if ($@) {
if (UNIVERSAL::isa($bref, "CODE")) {
unless ($need_queue) {
- $self->{write_buf_size}--; # code refs are worth 1
- shift @{$self->{write_buf}};
+ shift @$wbuf;
}
$bref->();
die "Write error: $@ <$bref>";
}
- my $to_write = $len - $self->{write_buf_offset};
- my $written = syswrite($self->{sock}, $$bref, $to_write,
- $self->{write_buf_offset});
+ my $off = $self->{wbuf_off} // 0;
+ my $to_write = $len - $off;
+ my $written = syswrite($sock, $$bref, $to_write, $off);
if (! defined $written) {
- if ($! == EPIPE) {
- return $self->close("EPIPE");
- } elsif ($! == EAGAIN) {
+ if ($! == EAGAIN) {
# since connection has stuff to write, it should now be
# interested in pending writes:
if ($need_queue) {
- push @{$self->{write_buf}}, $bref;
- $self->{write_buf_size} += $len;
+ push @$wbuf, $bref;
}
- $self->{write_set_watch} = 1 unless $self->{event_watch} & POLLOUT;
$self->watch_write(1);
return 0;
- } elsif ($! == ECONNRESET) {
- return $self->close("ECONNRESET");
}
- DebugLevel >= 1 && $self->debugmsg("Closing connection ($self) due to write error: $!\n");
-
- return $self->close("write_error");
+ return $self->close;
} elsif ($written != $to_write) {
- DebugLevel >= 2 && $self->debugmsg("Wrote PARTIAL %d bytes to %d",
- $written, $self->{fd});
if ($need_queue) {
- push @{$self->{write_buf}}, $bref;
- $self->{write_buf_size} += $len;
+ push @$wbuf, $bref;
}
# since connection has stuff to write, it should now be
# interested in pending writes:
- $self->{write_buf_offset} += $written;
- $self->{write_buf_size} -= $written;
- $self->on_incomplete_write;
+ $self->{wbuf_off} = $off + $written;
+ $self->watch_write(1);
return 0;
} elsif ($written == $to_write) {
- DebugLevel >= 2 && $self->debugmsg("Wrote ALL %d bytes to %d (nq=%d)",
- $written, $self->{fd}, $need_queue);
- $self->{write_buf_offset} = 0;
-
- if ($self->{write_set_watch}) {
- $self->watch_write(0);
- $self->{write_set_watch} = 0;
- }
+ delete $self->{wbuf_off};
+ $self->watch_write(0);
# this was our only write, so we can return immediately
# since we avoided incrementing the buffer size or
# can't be anything else to write.
return 1 if $need_queue;
- $self->{write_buf_size} -= $written;
- shift @{$self->{write_buf}};
+ shift @$wbuf;
undef $bref;
next WRITE;
}
}
}
-sub on_incomplete_write {
- my PublicInbox::DS $self = shift;
- $self->{write_set_watch} = 1 unless $self->{event_watch} & POLLOUT;
- $self->watch_write(1);
-}
-
-=head2 C<< $obj->read( $bytecount ) >>
-
-Read at most I<bytecount> bytes from the underlying handle; returns scalar
-ref on read, or undef on connection closed.
-
-=cut
-sub read {
- my PublicInbox::DS $self = shift;
- return if $self->{closed};
- my $bytes = shift;
- my $buf;
- my $sock = $self->{sock};
-
- # if this is too high, perl quits(!!). reports on mailing lists
- # don't seem to point to a universal answer. 5MB worked for some,
- # crashed for others. 1MB works for more people. let's go with 1MB
- # for now. :/
- my $req_bytes = $bytes > 1048576 ? 1048576 : $bytes;
-
- my $res = sysread($sock, $buf, $req_bytes, 0);
- DebugLevel >= 2 && $self->debugmsg("sysread = %d; \$! = %d", $res, $!);
-
- if (! $res && $! != EWOULDBLOCK) {
- # catches 0=conn closed or undef=error
- DebugLevel >= 2 && $self->debugmsg("Fd \#%d read hit the end of the road.", $self->{fd});
- return undef;
- }
-
- return \$buf;
-}
-
-=head2 (VIRTUAL) C<< $obj->event_read() >>
-
-Readable event handler. Concrete deriviatives of PublicInbox::DS should
-provide an implementation of this. The default implementation will die if
-called.
-
-=cut
-sub event_read { die "Base class event_read called for $_[0]\n"; }
-
-=head2 (VIRTUAL) C<< $obj->event_err() >>
-
-Error event handler. Concrete deriviatives of PublicInbox::DS should
-provide an implementation of this. The default implementation will die if
-called.
-
-=cut
-sub event_err { die "Base class event_err called for $_[0]\n"; }
-
-=head2 (VIRTUAL) C<< $obj->event_hup() >>
-
-'Hangup' event handler. Concrete deriviatives of PublicInbox::DS should
-provide an implementation of this. The default implementation will die if
-called.
-
-=cut
-sub event_hup { die "Base class event_hup called for $_[0]\n"; }
-
-=head2 C<< $obj->event_write() >>
-
-Writable event handler. Concrete deriviatives of PublicInbox::DS may wish to
-provide an implementation of this. The default implementation calls
-C<write()> with an C<undef>.
-
-=cut
-sub event_write {
- my $self = shift;
- $self->write(undef);
-}
-
=head2 C<< $obj->watch_read( $boolean ) >>
Turn 'readable' event notification on or off.
=cut
sub watch_read {
my PublicInbox::DS $self = shift;
- return if $self->{closed} || !$self->{sock};
+ my $sock = $self->{sock} or return;
my $val = shift;
my $event = $self->{event_watch};
$event &= ~POLLIN if ! $val;
$event |= POLLIN if $val;
+ my $fd = fileno($sock);
# If it changed, set it
if ($event != $self->{event_watch}) {
if ($HaveKQueue) {
- $KQueue->EV_SET($self->{fd}, IO::KQueue::EVFILT_READ(),
+ $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(),
$val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
}
elsif ($HaveEpoll) {
- epoll_ctl($Epoll, EPOLL_CTL_MOD, $self->{fd}, $event)
- and $self->dump_error("couldn't modify epoll settings for $self->{fd} " .
- "from $self->{event_watch} -> $event: $! (" . ($!+0) . ")");
+ epoll_ctl($Epoll, EPOLL_CTL_MOD, $fd, $event) and
+ confess("EPOLL_CTL_MOD: $!");
}
$self->{event_watch} = $event;
}
=cut
sub watch_write {
my PublicInbox::DS $self = shift;
- return if $self->{closed} || !$self->{sock};
+ my $sock = $self->{sock} or return;
my $val = shift;
my $event = $self->{event_watch};
$event &= ~POLLOUT if ! $val;
$event |= POLLOUT if $val;
-
- if ($val && caller ne __PACKAGE__) {
- # A subclass registered interest, it's now responsible for this.
- $self->{write_set_watch} = 0;
- }
+ my $fd = fileno($sock);
# If it changed, set it
if ($event != $self->{event_watch}) {
if ($HaveKQueue) {
- $KQueue->EV_SET($self->{fd}, IO::KQueue::EVFILT_WRITE(),
+ $KQueue->EV_SET($fd, IO::KQueue::EVFILT_WRITE(),
$val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
}
elsif ($HaveEpoll) {
- epoll_ctl($Epoll, EPOLL_CTL_MOD, $self->{fd}, $event)
- and $self->dump_error("couldn't modify epoll settings for $self->{fd} " .
- "from $self->{event_watch} -> $event: $! (" . ($!+0) . ")");
+ epoll_ctl($Epoll, EPOLL_CTL_MOD, $fd, $event) and
+ confess "EPOLL_CTL_MOD: $!";
}
$self->{event_watch} = $event;
}
}
-=head2 C<< $obj->dump_error( $message ) >>
-
-Prints to STDERR a backtrace with information about this socket and what lead
-up to the dump_error call.
-
-=cut
-sub dump_error {
- my $i = 0;
- my @list;
- while (my ($file, $line, $sub) = (caller($i++))[1..3]) {
- push @list, "\t$file:$line called $sub\n";
- }
-
- warn "ERROR: $_[1]\n" .
- "\t$_[0] = " . $_[0]->as_string . "\n" .
- join('', @list);
-}
-
-=head2 C<< $obj->debugmsg( $format, @args ) >>
-
-Print the debugging message specified by the C<sprintf>-style I<format> and
-I<args>.
-
-=cut
-sub debugmsg {
- my ( $self, $fmt, @args ) = @_;
- confess "Not an object" unless ref $self;
-
- chomp $fmt;
- printf STDERR ">>> $fmt\n", @args;
-}
-
-=head2 C<< $obj->as_string() >>
-
-Returns a string describing this socket.
-
-=cut
-sub as_string {
- my PublicInbox::DS $self = shift;
- my $rw = "(" . ($self->{event_watch} & POLLIN ? 'R' : '') .
- ($self->{event_watch} & POLLOUT ? 'W' : '') . ")";
- my $ret = ref($self) . "$rw: " . ($self->{closed} ? "closed" : "open");
- return $ret;
-}
-
package PublicInbox::DS::Timer;
# [$abs_float_firetime, $coderef];
sub cancel {