1 # This library is free software; you can redistribute it and/or modify
2 # it under the same terms as Perl itself.
4 # This license differs from the rest of public-inbox
6 # This is a fork of the (for now) unmaintained Danga::Socket 1.61.
7 # Unused features will be removed, and updates will be made to take
8 # advantage of newer kernels
10 package PublicInbox::DS;
16 use vars qw{$VERSION};
20 no warnings qw(deprecated);
22 use PublicInbox::Syscall qw(:epoll);
24 use fields ('sock', # underlying socket
25 'fd', # numeric file descriptor
26 'write_buf', # arrayref of scalars, scalarrefs, or coderefs to write
27 'write_buf_offset', # offset into first array of write_buf to start writing at
28 'write_buf_size', # total length of data in all write_buf items
29 'write_set_watch', # bool: true if we internally set watch_write rather than by a subclass
30 'closed', # bool: socket is closed
31 'event_watch', # bitmask of events the client is interested in (POLLIN,OUT,etc.)
32 'writer_func', # subref which does writing. must return bytes written (or undef) and set $! on errors
35 use Errno qw(EINPROGRESS EWOULDBLOCK EISCONN ENOTSOCK
36 EPIPE EAGAIN EBADF ECONNRESET ENOPROTOOPT);
37 use Socket qw(IPPROTO_TCP);
38 use Carp qw(croak confess);
40 use constant DebugLevel => 0;
42 use constant POLLIN => 1;
43 use constant POLLOUT => 4;
44 use constant POLLERR => 8;
45 use constant POLLHUP => 16;
46 use constant POLLNVAL => 32;
48 our $HAVE_KQUEUE = eval { require IO::KQueue; 1 };
51 $HaveEpoll, # Flag -- is epoll available? initially undefined.
53 %DescriptorMap, # fd (num) -> PublicInbox::DS object
54 $Epoll, # Global epoll fd (for epoll mode only)
55 $KQueue, # Global kqueue fd (for kqueue mode only)
56 @ToClose, # sockets to close when event loop is done
57 %OtherFds, # A hash of "other" (non-PublicInbox::DS) file
58 # descriptors for the event loop to track.
60 $PostLoopCallback, # subref to call at the end of each loop, if defined (global)
61 %PLCMap, # fd (num) -> PostLoopCallback (per-object)
63 $LoopTimeout, # timeout of event loop in milliseconds
64 $DoneInit, # if we've done the one-time module init yet
68 # this may be set to zero with old kernels
69 our $EPOLLEXCLUSIVE = EPOLLEXCLUSIVE;
72 #####################################################################
73 ### C L A S S M E T H O D S
74 #####################################################################
76 =head2 C<< CLASS->Reset() >>
85 $LoopTimeout = -1; # no timeout by default
88 $PostLoopCallback = undef;
92 POSIX::close($Epoll) if defined $Epoll && $Epoll >= 0;
93 POSIX::close($KQueue) if defined $KQueue && $KQueue >= 0;
95 *EventLoop = *FirstTimeEventLoop;
98 =head2 C<< CLASS->HaveEpoll() >>
100 Returns a true value if this class will use IO::Epoll for async IO.
108 =head2 C<< CLASS->WatchedSockets() >>
110 Returns the number of file descriptors which are registered with the global
115 return scalar keys %DescriptorMap;
117 *watched_sockets = *WatchedSockets;
119 =head2 C<< CLASS->ToClose() >>
121 Return the list of sockets that are awaiting close() at the end of the
125 sub ToClose { return @ToClose; }
127 =head2 C<< CLASS->OtherFds( [%fdmap] ) >>
129 Get/set the hash of file descriptors that need processing in parallel with
130 the registered PublicInbox::DS objects.
135 if ( @_ ) { %OtherFds = @_ }
136 return wantarray ? %OtherFds : \%OtherFds;
139 =head2 C<< CLASS->AddOtherFds( [%fdmap] ) >>
141 Add fds to the OtherFds hash for processing.
146 %OtherFds = ( %OtherFds, @_ ); # FIXME investigate what happens on dupe fds
147 return wantarray ? %OtherFds : \%OtherFds;
150 =head2 C<< CLASS->SetLoopTimeout( $timeout ) >>
152 Set the loop timeout for the event loop to some value in milliseconds.
154 A timeout of 0 (zero) means poll forever. A timeout of -1 means poll and return
159 return $LoopTimeout = $_[1] + 0;
162 =head2 C<< CLASS->DebugMsg( $format, @args ) >>
164 Print the debugging message specified by the C<sprintf>-style I<format> and
169 my ( $class, $fmt, @args ) = @_;
171 printf STDERR ">>> $fmt\n", @args;
174 =head2 C<< CLASS->AddTimer( $seconds, $coderef ) >>
176 Add a timer to occur $seconds from now. $seconds may be fractional, but timers
177 are not guaranteed to fire at the exact time you ask for.
179 Returns a timer object which you can call C<< $timer->cancel >> on if you need to.
184 my ($secs, $coderef) = @_;
186 my $fire_time = Time::HiRes::time() + $secs;
188 my $timer = bless [$fire_time, $coderef], "PublicInbox::DS::Timer";
190 if (!@Timers || $fire_time >= $Timers[-1][0]) {
191 push @Timers, $timer;
195 # Now, where do we insert? (NOTE: this appears slow, algorithm-wise,
196 # but it was compared against calendar queues, heaps, naive push/sort,
197 # and a bunch of other versions, and found to be fastest with a large
198 # variety of datasets.)
199 for (my $i = 0; $i < @Timers; $i++) {
200 if ($Timers[$i][0] > $fire_time) {
201 splice(@Timers, $i, 0, $timer);
206 die "Shouldn't get here.";
209 =head2 C<< CLASS->DescriptorMap() >>
211 Get the hash of PublicInbox::DS objects keyed by the file descriptor (fileno) they
214 Returns a hash in list context or a hashref in scalar context.
218 return wantarray ? %DescriptorMap : \%DescriptorMap;
220 *descriptor_map = *DescriptorMap;
221 *get_sock_ref = *DescriptorMap;
229 $KQueue = IO::KQueue->new();
230 $HaveKQueue = $KQueue >= 0;
232 *EventLoop = *KQueueEventLoop;
235 elsif (PublicInbox::Syscall::epoll_defined()) {
236 $Epoll = eval { epoll_create(1024); };
237 $HaveEpoll = defined $Epoll && $Epoll >= 0;
239 *EventLoop = *EpollEventLoop;
243 if (!$HaveEpoll && !$HaveKQueue) {
245 *EventLoop = *PollEventLoop;
249 =head2 C<< CLASS->EventLoop() >>
251 Start processing IO events. In most daemon programs this never exits. See
252 C<PostLoopCallback> below for how to exit the loop.
255 sub FirstTimeEventLoop {
261 EpollEventLoop($class);
262 } elsif ($HaveKQueue) {
263 KQueueEventLoop($class);
265 PollEventLoop($class);
269 # runs timers and returns milliseconds for next one, or next event loop
271 return $LoopTimeout unless @Timers;
273 my $now = Time::HiRes::time();
276 while (@Timers && $Timers[0][0] <= $now) {
277 my $to_run = shift(@Timers);
278 $to_run->[1]->($now) if $to_run->[1];
281 return $LoopTimeout unless @Timers;
283 # convert time to an even number of milliseconds, adding 1
284 # extra, otherwise floating point fun can occur and we'll
285 # call RunTimers like 20-30 times, each returning a timeout
286 # of 0.0000212 seconds
287 my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
289 # -1 is an infinite timeout, so prefer a real timeout
290 return $timeout if $LoopTimeout == -1;
292 # otherwise pick the lower of our regular timeout and time until
294 return $LoopTimeout if $LoopTimeout < $timeout;
298 ### The epoll-based event loop. Gets installed as EventLoop if IO::Epoll loads
303 foreach my $fd ( keys %OtherFds ) {
304 if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, EPOLLIN) == -1) {
305 warn "epoll_ctl(): failure adding fd=$fd; $! (", $!+0, ")\n";
312 my $timeout = RunTimers();
314 # get up to 1000 events
315 my $evcount = epoll_wait($Epoll, 1000, $timeout, \@events);
317 for ($i=0; $i<$evcount; $i++) {
318 my $ev = $events[$i];
320 # it's possible epoll_wait returned many events, including some at the end
321 # that ones in the front triggered unregister-interest actions. if we
322 # can't find the %sock entry, it's because we're no longer interested
324 my PublicInbox::DS $pob = $DescriptorMap{$ev->[0]};
326 my $state = $ev->[1];
328 # if we didn't find a Perlbal::Socket subclass for that fd, try other
329 # pseudo-registered (above) fds.
331 if (my $code = $OtherFds{$ev->[0]}) {
335 warn "epoll() returned fd $fd w/ state $state for which we have no mapping. removing.\n";
337 epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, 0);
342 DebugLevel >= 1 && $class->DebugMsg("Event: fd=%d (%s), state=%d \@ %s\n",
343 $ev->[0], ref($pob), $ev->[1], time);
345 # standard non-profiling codepat
346 $pob->event_read if $state & EPOLLIN && ! $pob->{closed};
347 $pob->event_write if $state & EPOLLOUT && ! $pob->{closed};
348 if ($state & (EPOLLERR|EPOLLHUP)) {
349 $pob->event_err if $state & EPOLLERR && ! $pob->{closed};
350 $pob->event_hup if $state & EPOLLHUP && ! $pob->{closed};
353 return unless PostEventLoop();
358 ### The fallback IO::Poll-based event loop. Gets installed as EventLoop if
359 ### IO::Epoll fails to load.
363 my PublicInbox::DS $pob;
366 my $timeout = RunTimers();
368 # the following sets up @poll as a series of ($poll,$event_mask)
369 # items, then uses IO::Poll::_poll, implemented in XS, which
370 # modifies the array in place with the even elements being
371 # replaced with the event masks that occured.
373 foreach my $fd ( keys %OtherFds ) {
374 push @poll, $fd, POLLIN;
376 while ( my ($fd, $sock) = each %DescriptorMap ) {
377 push @poll, $fd, $sock->{event_watch};
380 # if nothing to poll, either end immediately (if no timeout)
381 # or just keep calling the callback
383 select undef, undef, undef, ($timeout / 1000);
384 return unless PostEventLoop();
388 my $count = IO::Poll::_poll($timeout, @poll);
390 return unless PostEventLoop();
394 # Fetch handles with read events
396 my ($fd, $state) = splice(@poll, 0, 2);
399 $pob = $DescriptorMap{$fd};
402 if (my $code = $OtherFds{$fd}) {
408 $pob->event_read if $state & POLLIN && ! $pob->{closed};
409 $pob->event_write if $state & POLLOUT && ! $pob->{closed};
410 $pob->event_err if $state & POLLERR && ! $pob->{closed};
411 $pob->event_hup if $state & POLLHUP && ! $pob->{closed};
414 return unless PostEventLoop();
420 ### The kqueue-based event loop. Gets installed as EventLoop if IO::KQueue works
422 sub KQueueEventLoop {
425 foreach my $fd (keys %OtherFds) {
426 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(), IO::KQueue::EV_ADD());
430 my $timeout = RunTimers();
431 my @ret = $KQueue->kevent($timeout);
433 foreach my $kev (@ret) {
434 my ($fd, $filter, $flags, $fflags) = @$kev;
435 my PublicInbox::DS $pob = $DescriptorMap{$fd};
437 if (my $code = $OtherFds{$fd}) {
440 warn "kevent() returned fd $fd for which we have no mapping. removing.\n";
441 POSIX::close($fd); # close deletes the kevent entry
446 DebugLevel >= 1 && $class->DebugMsg("Event: fd=%d (%s), flags=%d \@ %s\n",
447 $fd, ref($pob), $flags, time);
449 $pob->event_read if $filter == IO::KQueue::EVFILT_READ() && !$pob->{closed};
450 $pob->event_write if $filter == IO::KQueue::EVFILT_WRITE() && !$pob->{closed};
451 if ($flags == IO::KQueue::EV_EOF() && !$pob->{closed}) {
459 return unless PostEventLoop();
465 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
467 Sets post loop callback function. Pass a subref and it will be
468 called every time the event loop finishes.
470 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
473 The callback function will be passed two parameters: \%DescriptorMap, \%OtherFds.
476 sub SetPostLoopCallback {
477 my ($class, $ref) = @_;
480 # per-object callback
481 my PublicInbox::DS $self = $class;
482 if (defined $ref && ref $ref eq 'CODE') {
483 $PLCMap{$self->{fd}} = $ref;
485 delete $PLCMap{$self->{fd}};
489 $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
493 # Internal function: run the post-event callback, send read events
494 # for pushed-back data, and close pending connections. returns 1
495 # if event loop should continue, or 0 to shut it all down.
497 # now we can close sockets that wanted to close during our event processing.
498 # (we didn't want to close them during the loop, as we didn't want fd numbers
499 # being reused and confused during the event loop)
500 while (my $sock = shift @ToClose) {
501 my $fd = fileno($sock);
503 # close the socket. (not a PublicInbox::DS close)
506 # and now we can finally remove the fd from the map. see
507 # comment above in _cleanup.
508 delete $DescriptorMap{$fd};
512 # by default we keep running, unless a postloop callback (either per-object
513 # or global) cancels it
514 my $keep_running = 1;
516 # per-object post-loop-callbacks
517 for my $plc (values %PLCMap) {
518 $keep_running &&= $plc->(\%DescriptorMap, \%OtherFds);
521 # now we're at the very end, call callback if defined
522 if (defined $PostLoopCallback) {
523 $keep_running &&= $PostLoopCallback->(\%DescriptorMap, \%OtherFds);
526 return $keep_running;
529 #####################################################################
530 ### PublicInbox::DS-the-object code
531 #####################################################################
533 =head2 OBJECT METHODS
535 =head2 C<< CLASS->new( $socket ) >>
537 Create a new PublicInbox::DS subclass object for the given I<socket> which will
538 react to events on it during the C<EventLoop>.
540 This is normally (always?) called from your subclass via:
542 $class->SUPER::new($socket);
546 my ($self, $sock, $exclusive) = @_;
547 $self = fields::new($self) unless ref $self;
549 $self->{sock} = $sock;
550 my $fd = fileno($sock);
552 Carp::cluck("undef sock and/or fd in PublicInbox::DS->new. sock=" . ($sock || "") . ", fd=" . ($fd || ""))
556 $self->{write_buf} = [];
557 $self->{write_buf_offset} = 0;
558 $self->{write_buf_size} = 0;
561 my $ev = $self->{event_watch} = POLLERR|POLLHUP|POLLNVAL;
567 $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP|$EPOLLEXCLUSIVE;
570 if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
571 if ($!{EINVAL} && ($ev & $EPOLLEXCLUSIVE)) {
572 $EPOLLEXCLUSIVE = 0; # old kernel
573 $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP;
576 die "couldn't add epoll watch for $fd: $!\n";
579 elsif ($HaveKQueue) {
580 # Add them to the queue but disabled for now
581 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(),
582 IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
583 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_WRITE(),
584 IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
587 Carp::cluck("PublicInbox::DS::new blowing away existing descriptor map for fd=$fd ($DescriptorMap{$fd})")
588 if $DescriptorMap{$fd};
590 $DescriptorMap{$fd} = $self;
595 #####################################################################
596 ### I N S T A N C E M E T H O D S
597 #####################################################################
599 =head2 C<< $obj->steal_socket() >>
601 Basically returns our socket and makes it so that we don't try to close it,
602 but we do remove it from epoll handlers. THIS CLOSES $self. It is the same
603 thing as calling close, except it gives you the socket to use.
607 my PublicInbox::DS $self = $_[0];
608 return if $self->{closed};
610 # cleanup does most of the work of closing this socket
613 # now undef our internal sock and fd structures so we don't use them
614 my $sock = $self->{sock};
615 $self->{sock} = undef;
619 =head2 C<< $obj->close( [$reason] ) >>
621 Close the socket. The I<reason> argument will be used in debugging messages.
625 my PublicInbox::DS $self = $_[0];
626 return if $self->{closed};
628 # print out debugging info for this close
630 my ($pkg, $filename, $line) = caller;
631 my $reason = $_[1] || "";
632 warn "Closing \#$self->{fd} due to $pkg/$filename/$line ($reason)\n";
635 # this does most of the work of closing us
638 # defer closing the actual socket until the event loop is done
639 # processing this round of events. (otherwise we might reuse fds)
641 push @ToClose, $self->{sock};
642 $self->{sock} = undef;
648 ### METHOD: _cleanup()
649 ### Called by our closers so we can clean internal data structures.
651 my PublicInbox::DS $self = $_[0];
653 # we're effectively closed; we have no fd and sock when we leave here
656 # we need to flush our write buffer, as there may
657 # be self-referential closures (sub { $client->close })
658 # preventing the object from being destroyed
659 $self->{write_buf} = [];
661 # if we're using epoll, we have to remove this from our epoll fd so we stop getting
662 # notifications about it
663 if ($HaveEpoll && $self->{fd}) {
664 if (epoll_ctl($Epoll, EPOLL_CTL_DEL, $self->{fd}, $self->{event_watch}) != 0) {
665 # dump_error prints a backtrace so we can try to figure out why this happened
666 $self->dump_error("epoll_ctl(): failure deleting fd=$self->{fd} during _cleanup(); $! (" . ($!+0) . ")");
670 # now delete from mappings. this fd no longer belongs to us, so we don't want
671 # to get alerts for it if it becomes writable/readable/etc.
672 delete $PLCMap{$self->{fd}};
674 # we explicitly don't delete from DescriptorMap here until we
675 # actually close the socket, as we might be in the middle of
676 # processing an epoll_wait/etc that returned hundreds of fds, one
677 # of which is not yet processed and is what we're closing. if we
678 # keep it in DescriptorMap, then the event harnesses can just
679 # looked at $pob->{closed} and ignore it. but if it's an
680 # un-accounted for fd, then it (understandably) freak out a bit
681 # and emit warnings, thinking their state got off.
683 # and finally get rid of our fd so we can't use it anywhere else
687 =head2 C<< $obj->sock() >>
689 Returns the underlying IO::Handle for the object.
693 my PublicInbox::DS $self = shift;
694 return $self->{sock};
697 =head2 C<< $obj->set_writer_func( CODEREF ) >>
699 Sets a function to use instead of C<syswrite()> when writing data to the socket.
702 sub set_writer_func {
703 my PublicInbox::DS $self = shift;
705 Carp::croak("Not a subref") unless !defined $wtr || UNIVERSAL::isa($wtr, "CODE");
706 $self->{writer_func} = $wtr;
709 =head2 C<< $obj->write( $data ) >>
711 Write the specified data to the underlying handle. I<data> may be scalar,
712 scalar ref, code ref (to run when there), or undef just to kick-start.
713 Returns 1 if writes all went through, or 0 if there are writes in queue. If
714 it returns 1, caller should stop waiting for 'writable' events)
718 my PublicInbox::DS $self;
722 # nobody should be writing to closed sockets, but caller code can
723 # do two writes within an event, have the first fail and
724 # disconnect the other side (whose destructor then closes the
725 # calling object, but it's still in a method), and then the
726 # now-dead object does its second write. that is this case. we
727 # just lie and say it worked. it'll be dead soon and won't be
729 return 1 if $self->{closed};
733 # just queue data if there's already a wait
737 $bref = ref $data ? $data : \$data;
738 if ($self->{write_buf_size}) {
739 push @{$self->{write_buf}}, $bref;
740 $self->{write_buf_size} += ref $bref eq "SCALAR" ? length($$bref) : 1;
744 # this flag says we're bypassing the queue system, knowing we're the
745 # only outstanding write, and hoping we don't ever need to use it.
746 # if so later, though, we'll need to queue
752 return 1 unless $bref ||= $self->{write_buf}[0];
756 $len = length($$bref); # this will die if $bref is a code ref, caught below
759 if (UNIVERSAL::isa($bref, "CODE")) {
760 unless ($need_queue) {
761 $self->{write_buf_size}--; # code refs are worth 1
762 shift @{$self->{write_buf}};
766 # code refs are just run and never get reenqueued
767 # (they're one-shot), so turn off the flag indicating the
768 # outstanding data needs queueing.
774 die "Write error: $@ <$bref>";
777 my $to_write = $len - $self->{write_buf_offset};
779 if (my $wtr = $self->{writer_func}) {
780 $written = $wtr->($bref, $to_write, $self->{write_buf_offset});
782 $written = syswrite($self->{sock}, $$bref, $to_write, $self->{write_buf_offset});
785 if (! defined $written) {
787 return $self->close("EPIPE");
788 } elsif ($! == EAGAIN) {
789 # since connection has stuff to write, it should now be
790 # interested in pending writes:
792 push @{$self->{write_buf}}, $bref;
793 $self->{write_buf_size} += $len;
795 $self->{write_set_watch} = 1 unless $self->{event_watch} & POLLOUT;
796 $self->watch_write(1);
798 } elsif ($! == ECONNRESET) {
799 return $self->close("ECONNRESET");
802 DebugLevel >= 1 && $self->debugmsg("Closing connection ($self) due to write error: $!\n");
804 return $self->close("write_error");
805 } elsif ($written != $to_write) {
806 DebugLevel >= 2 && $self->debugmsg("Wrote PARTIAL %d bytes to %d",
807 $written, $self->{fd});
809 push @{$self->{write_buf}}, $bref;
810 $self->{write_buf_size} += $len;
812 # since connection has stuff to write, it should now be
813 # interested in pending writes:
814 $self->{write_buf_offset} += $written;
815 $self->{write_buf_size} -= $written;
816 $self->on_incomplete_write;
818 } elsif ($written == $to_write) {
819 DebugLevel >= 2 && $self->debugmsg("Wrote ALL %d bytes to %d (nq=%d)",
820 $written, $self->{fd}, $need_queue);
821 $self->{write_buf_offset} = 0;
823 if ($self->{write_set_watch}) {
824 $self->watch_write(0);
825 $self->{write_set_watch} = 0;
828 # this was our only write, so we can return immediately
829 # since we avoided incrementing the buffer size or
830 # putting it in the buffer. we also know there
831 # can't be anything else to write.
832 return 1 if $need_queue;
834 $self->{write_buf_size} -= $written;
835 shift @{$self->{write_buf}};
842 sub on_incomplete_write {
843 my PublicInbox::DS $self = shift;
844 $self->{write_set_watch} = 1 unless $self->{event_watch} & POLLOUT;
845 $self->watch_write(1);
848 =head2 C<< $obj->read( $bytecount ) >>
850 Read at most I<bytecount> bytes from the underlying handle; returns scalar
851 ref on read, or undef on connection closed.
855 my PublicInbox::DS $self = shift;
856 return if $self->{closed};
859 my $sock = $self->{sock};
861 # if this is too high, perl quits(!!). reports on mailing lists
862 # don't seem to point to a universal answer. 5MB worked for some,
863 # crashed for others. 1MB works for more people. let's go with 1MB
865 my $req_bytes = $bytes > 1048576 ? 1048576 : $bytes;
867 my $res = sysread($sock, $buf, $req_bytes, 0);
868 DebugLevel >= 2 && $self->debugmsg("sysread = %d; \$! = %d", $res, $!);
870 if (! $res && $! != EWOULDBLOCK) {
871 # catches 0=conn closed or undef=error
872 DebugLevel >= 2 && $self->debugmsg("Fd \#%d read hit the end of the road.", $self->{fd});
879 =head2 (VIRTUAL) C<< $obj->event_read() >>
881 Readable event handler. Concrete deriviatives of PublicInbox::DS should
882 provide an implementation of this. The default implementation will die if
886 sub event_read { die "Base class event_read called for $_[0]\n"; }
888 =head2 (VIRTUAL) C<< $obj->event_err() >>
890 Error event handler. Concrete deriviatives of PublicInbox::DS should
891 provide an implementation of this. The default implementation will die if
895 sub event_err { die "Base class event_err called for $_[0]\n"; }
897 =head2 (VIRTUAL) C<< $obj->event_hup() >>
899 'Hangup' event handler. Concrete deriviatives of PublicInbox::DS should
900 provide an implementation of this. The default implementation will die if
904 sub event_hup { die "Base class event_hup called for $_[0]\n"; }
906 =head2 C<< $obj->event_write() >>
908 Writable event handler. Concrete deriviatives of PublicInbox::DS may wish to
909 provide an implementation of this. The default implementation calls
910 C<write()> with an C<undef>.
918 =head2 C<< $obj->watch_read( $boolean ) >>
920 Turn 'readable' event notification on or off.
924 my PublicInbox::DS $self = shift;
925 return if $self->{closed} || !$self->{sock};
928 my $event = $self->{event_watch};
930 $event &= ~POLLIN if ! $val;
931 $event |= POLLIN if $val;
933 # If it changed, set it
934 if ($event != $self->{event_watch}) {
936 $KQueue->EV_SET($self->{fd}, IO::KQueue::EVFILT_READ(),
937 $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
940 epoll_ctl($Epoll, EPOLL_CTL_MOD, $self->{fd}, $event)
941 and $self->dump_error("couldn't modify epoll settings for $self->{fd} " .
942 "from $self->{event_watch} -> $event: $! (" . ($!+0) . ")");
944 $self->{event_watch} = $event;
948 =head2 C<< $obj->watch_write( $boolean ) >>
950 Turn 'writable' event notification on or off.
954 my PublicInbox::DS $self = shift;
955 return if $self->{closed} || !$self->{sock};
958 my $event = $self->{event_watch};
960 $event &= ~POLLOUT if ! $val;
961 $event |= POLLOUT if $val;
963 if ($val && caller ne __PACKAGE__) {
964 # A subclass registered interest, it's now responsible for this.
965 $self->{write_set_watch} = 0;
968 # If it changed, set it
969 if ($event != $self->{event_watch}) {
971 $KQueue->EV_SET($self->{fd}, IO::KQueue::EVFILT_WRITE(),
972 $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
975 epoll_ctl($Epoll, EPOLL_CTL_MOD, $self->{fd}, $event)
976 and $self->dump_error("couldn't modify epoll settings for $self->{fd} " .
977 "from $self->{event_watch} -> $event: $! (" . ($!+0) . ")");
979 $self->{event_watch} = $event;
983 =head2 C<< $obj->dump_error( $message ) >>
985 Prints to STDERR a backtrace with information about this socket and what lead
986 up to the dump_error call.
992 while (my ($file, $line, $sub) = (caller($i++))[1..3]) {
993 push @list, "\t$file:$line called $sub\n";
996 warn "ERROR: $_[1]\n" .
997 "\t$_[0] = " . $_[0]->as_string . "\n" .
1001 =head2 C<< $obj->debugmsg( $format, @args ) >>
1003 Print the debugging message specified by the C<sprintf>-style I<format> and
1008 my ( $self, $fmt, @args ) = @_;
1009 confess "Not an object" unless ref $self;
1012 printf STDERR ">>> $fmt\n", @args;
1015 =head2 C<< $obj->as_string() >>
1017 Returns a string describing this socket.
1021 my PublicInbox::DS $self = shift;
1022 my $rw = "(" . ($self->{event_watch} & POLLIN ? 'R' : '') .
1023 ($self->{event_watch} & POLLOUT ? 'W' : '') . ")";
1024 my $ret = ref($self) . "$rw: " . ($self->{closed} ? "closed" : "open");
1029 return undef unless $ENV{DS_DEBUG};
1030 my $msg = shift || "";
1031 warn "PublicInbox::DS: $msg\n";
1035 package PublicInbox::DS::Timer;
1036 # [$abs_float_firetime, $coderef];
1043 =head1 AUTHORS (Danga::Socket)
1045 Brad Fitzpatrick <brad@danga.com> - author
1047 Michael Granger <ged@danga.com> - docs, testing
1049 Mark Smith <junior@danga.com> - contributor, heavy user, testing
1051 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits