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->ToClose() >>
110 Return the list of sockets that are awaiting close() at the end of the
114 sub ToClose { return @ToClose; }
116 =head2 C<< CLASS->OtherFds( [%fdmap] ) >>
118 Get/set the hash of file descriptors that need processing in parallel with
119 the registered PublicInbox::DS objects.
124 if ( @_ ) { %OtherFds = @_ }
125 return wantarray ? %OtherFds : \%OtherFds;
128 =head2 C<< CLASS->AddOtherFds( [%fdmap] ) >>
130 Add fds to the OtherFds hash for processing.
135 %OtherFds = ( %OtherFds, @_ ); # FIXME investigate what happens on dupe fds
136 return wantarray ? %OtherFds : \%OtherFds;
139 =head2 C<< CLASS->SetLoopTimeout( $timeout ) >>
141 Set the loop timeout for the event loop to some value in milliseconds.
143 A timeout of 0 (zero) means poll forever. A timeout of -1 means poll and return
148 return $LoopTimeout = $_[1] + 0;
151 =head2 C<< CLASS->DebugMsg( $format, @args ) >>
153 Print the debugging message specified by the C<sprintf>-style I<format> and
158 my ( $class, $fmt, @args ) = @_;
160 printf STDERR ">>> $fmt\n", @args;
163 =head2 C<< CLASS->AddTimer( $seconds, $coderef ) >>
165 Add a timer to occur $seconds from now. $seconds may be fractional, but timers
166 are not guaranteed to fire at the exact time you ask for.
168 Returns a timer object which you can call C<< $timer->cancel >> on if you need to.
173 my ($secs, $coderef) = @_;
175 my $fire_time = Time::HiRes::time() + $secs;
177 my $timer = bless [$fire_time, $coderef], "PublicInbox::DS::Timer";
179 if (!@Timers || $fire_time >= $Timers[-1][0]) {
180 push @Timers, $timer;
184 # Now, where do we insert? (NOTE: this appears slow, algorithm-wise,
185 # but it was compared against calendar queues, heaps, naive push/sort,
186 # and a bunch of other versions, and found to be fastest with a large
187 # variety of datasets.)
188 for (my $i = 0; $i < @Timers; $i++) {
189 if ($Timers[$i][0] > $fire_time) {
190 splice(@Timers, $i, 0, $timer);
195 die "Shouldn't get here.";
204 $KQueue = IO::KQueue->new();
205 $HaveKQueue = $KQueue >= 0;
207 *EventLoop = *KQueueEventLoop;
210 elsif (PublicInbox::Syscall::epoll_defined()) {
211 $Epoll = eval { epoll_create(1024); };
212 $HaveEpoll = defined $Epoll && $Epoll >= 0;
214 *EventLoop = *EpollEventLoop;
218 if (!$HaveEpoll && !$HaveKQueue) {
220 *EventLoop = *PollEventLoop;
224 =head2 C<< CLASS->EventLoop() >>
226 Start processing IO events. In most daemon programs this never exits. See
227 C<PostLoopCallback> below for how to exit the loop.
230 sub FirstTimeEventLoop {
236 EpollEventLoop($class);
237 } elsif ($HaveKQueue) {
238 KQueueEventLoop($class);
240 PollEventLoop($class);
244 # runs timers and returns milliseconds for next one, or next event loop
246 return $LoopTimeout unless @Timers;
248 my $now = Time::HiRes::time();
251 while (@Timers && $Timers[0][0] <= $now) {
252 my $to_run = shift(@Timers);
253 $to_run->[1]->($now) if $to_run->[1];
256 return $LoopTimeout unless @Timers;
258 # convert time to an even number of milliseconds, adding 1
259 # extra, otherwise floating point fun can occur and we'll
260 # call RunTimers like 20-30 times, each returning a timeout
261 # of 0.0000212 seconds
262 my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
264 # -1 is an infinite timeout, so prefer a real timeout
265 return $timeout if $LoopTimeout == -1;
267 # otherwise pick the lower of our regular timeout and time until
269 return $LoopTimeout if $LoopTimeout < $timeout;
273 ### The epoll-based event loop. Gets installed as EventLoop if IO::Epoll loads
278 foreach my $fd ( keys %OtherFds ) {
279 if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, EPOLLIN) == -1) {
280 warn "epoll_ctl(): failure adding fd=$fd; $! (", $!+0, ")\n";
287 my $timeout = RunTimers();
289 # get up to 1000 events
290 my $evcount = epoll_wait($Epoll, 1000, $timeout, \@events);
292 for ($i=0; $i<$evcount; $i++) {
293 my $ev = $events[$i];
295 # it's possible epoll_wait returned many events, including some at the end
296 # that ones in the front triggered unregister-interest actions. if we
297 # can't find the %sock entry, it's because we're no longer interested
299 my PublicInbox::DS $pob = $DescriptorMap{$ev->[0]};
301 my $state = $ev->[1];
303 # if we didn't find a Perlbal::Socket subclass for that fd, try other
304 # pseudo-registered (above) fds.
306 if (my $code = $OtherFds{$ev->[0]}) {
310 warn "epoll() returned fd $fd w/ state $state for which we have no mapping. removing.\n";
311 epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, 0);
317 DebugLevel >= 1 && $class->DebugMsg("Event: fd=%d (%s), state=%d \@ %s\n",
318 $ev->[0], ref($pob), $ev->[1], time);
320 # standard non-profiling codepat
321 $pob->event_read if $state & EPOLLIN && ! $pob->{closed};
322 $pob->event_write if $state & EPOLLOUT && ! $pob->{closed};
323 if ($state & (EPOLLERR|EPOLLHUP)) {
324 $pob->event_err if $state & EPOLLERR && ! $pob->{closed};
325 $pob->event_hup if $state & EPOLLHUP && ! $pob->{closed};
328 return unless PostEventLoop();
333 ### The fallback IO::Poll-based event loop. Gets installed as EventLoop if
334 ### IO::Epoll fails to load.
338 my PublicInbox::DS $pob;
341 my $timeout = RunTimers();
343 # the following sets up @poll as a series of ($poll,$event_mask)
344 # items, then uses IO::Poll::_poll, implemented in XS, which
345 # modifies the array in place with the even elements being
346 # replaced with the event masks that occured.
348 foreach my $fd ( keys %OtherFds ) {
349 push @poll, $fd, POLLIN;
351 while ( my ($fd, $sock) = each %DescriptorMap ) {
352 push @poll, $fd, $sock->{event_watch};
355 # if nothing to poll, either end immediately (if no timeout)
356 # or just keep calling the callback
358 select undef, undef, undef, ($timeout / 1000);
359 return unless PostEventLoop();
363 my $count = IO::Poll::_poll($timeout, @poll);
364 unless ($count >= 0) {
365 return unless PostEventLoop();
369 # Fetch handles with read events
371 my ($fd, $state) = splice(@poll, 0, 2);
374 $pob = $DescriptorMap{$fd};
377 if (my $code = $OtherFds{$fd}) {
383 $pob->event_read if $state & POLLIN && ! $pob->{closed};
384 $pob->event_write if $state & POLLOUT && ! $pob->{closed};
385 $pob->event_err if $state & POLLERR && ! $pob->{closed};
386 $pob->event_hup if $state & POLLHUP && ! $pob->{closed};
389 return unless PostEventLoop();
395 ### The kqueue-based event loop. Gets installed as EventLoop if IO::KQueue works
397 sub KQueueEventLoop {
400 foreach my $fd (keys %OtherFds) {
401 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(), IO::KQueue::EV_ADD());
405 my $timeout = RunTimers();
406 my @ret = eval { $KQueue->kevent($timeout) };
408 # workaround https://rt.cpan.org/Ticket/Display.html?id=116615
409 if ($err =~ /Interrupted system call/) {
416 foreach my $kev (@ret) {
417 my ($fd, $filter, $flags, $fflags) = @$kev;
418 my PublicInbox::DS $pob = $DescriptorMap{$fd};
420 if (my $code = $OtherFds{$fd}) {
423 warn "kevent() returned fd $fd for which we have no mapping. removing.\n";
424 POSIX::close($fd); # close deletes the kevent entry
429 DebugLevel >= 1 && $class->DebugMsg("Event: fd=%d (%s), flags=%d \@ %s\n",
430 $fd, ref($pob), $flags, time);
432 $pob->event_read if $filter == IO::KQueue::EVFILT_READ() && !$pob->{closed};
433 $pob->event_write if $filter == IO::KQueue::EVFILT_WRITE() && !$pob->{closed};
434 if ($flags == IO::KQueue::EV_EOF() && !$pob->{closed}) {
442 return unless PostEventLoop();
448 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
450 Sets post loop callback function. Pass a subref and it will be
451 called every time the event loop finishes.
453 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
456 The callback function will be passed two parameters: \%DescriptorMap, \%OtherFds.
459 sub SetPostLoopCallback {
460 my ($class, $ref) = @_;
463 # per-object callback
464 my PublicInbox::DS $self = $class;
465 if (defined $ref && ref $ref eq 'CODE') {
466 $PLCMap{$self->{fd}} = $ref;
468 delete $PLCMap{$self->{fd}};
472 $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
476 # Internal function: run the post-event callback, send read events
477 # for pushed-back data, and close pending connections. returns 1
478 # if event loop should continue, or 0 to shut it all down.
480 # now we can close sockets that wanted to close during our event processing.
481 # (we didn't want to close them during the loop, as we didn't want fd numbers
482 # being reused and confused during the event loop)
483 while (my $sock = shift @ToClose) {
484 my $fd = fileno($sock);
486 # close the socket. (not a PublicInbox::DS close)
489 # and now we can finally remove the fd from the map. see
490 # comment above in _cleanup.
491 delete $DescriptorMap{$fd};
495 # by default we keep running, unless a postloop callback (either per-object
496 # or global) cancels it
497 my $keep_running = 1;
499 # per-object post-loop-callbacks
500 for my $plc (values %PLCMap) {
501 $keep_running &&= $plc->(\%DescriptorMap, \%OtherFds);
504 # now we're at the very end, call callback if defined
505 if (defined $PostLoopCallback) {
506 $keep_running &&= $PostLoopCallback->(\%DescriptorMap, \%OtherFds);
509 return $keep_running;
512 #####################################################################
513 ### PublicInbox::DS-the-object code
514 #####################################################################
516 =head2 OBJECT METHODS
518 =head2 C<< CLASS->new( $socket ) >>
520 Create a new PublicInbox::DS subclass object for the given I<socket> which will
521 react to events on it during the C<EventLoop>.
523 This is normally (always?) called from your subclass via:
525 $class->SUPER::new($socket);
529 my ($self, $sock, $exclusive) = @_;
530 $self = fields::new($self) unless ref $self;
532 $self->{sock} = $sock;
533 my $fd = fileno($sock);
535 Carp::cluck("undef sock and/or fd in PublicInbox::DS->new. sock=" . ($sock || "") . ", fd=" . ($fd || ""))
539 $self->{write_buf} = [];
540 $self->{write_buf_offset} = 0;
541 $self->{write_buf_size} = 0;
544 my $ev = $self->{event_watch} = POLLERR|POLLHUP|POLLNVAL;
550 $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP|$EPOLLEXCLUSIVE;
553 if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
554 if ($!{EINVAL} && ($ev & $EPOLLEXCLUSIVE)) {
555 $EPOLLEXCLUSIVE = 0; # old kernel
556 $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP;
559 die "couldn't add epoll watch for $fd: $!\n";
562 elsif ($HaveKQueue) {
563 # Add them to the queue but disabled for now
564 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(),
565 IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
566 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_WRITE(),
567 IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
570 Carp::cluck("PublicInbox::DS::new blowing away existing descriptor map for fd=$fd ($DescriptorMap{$fd})")
571 if $DescriptorMap{$fd};
573 $DescriptorMap{$fd} = $self;
578 #####################################################################
579 ### I N S T A N C E M E T H O D S
580 #####################################################################
582 =head2 C<< $obj->steal_socket() >>
584 Basically returns our socket and makes it so that we don't try to close it,
585 but we do remove it from epoll handlers. THIS CLOSES $self. It is the same
586 thing as calling close, except it gives you the socket to use.
590 my PublicInbox::DS $self = $_[0];
591 return if $self->{closed};
593 # cleanup does most of the work of closing this socket
596 # now undef our internal sock and fd structures so we don't use them
597 my $sock = $self->{sock};
598 $self->{sock} = undef;
602 =head2 C<< $obj->close( [$reason] ) >>
604 Close the socket. The I<reason> argument will be used in debugging messages.
608 my PublicInbox::DS $self = $_[0];
609 return if $self->{closed};
611 # print out debugging info for this close
613 my ($pkg, $filename, $line) = caller;
614 my $reason = $_[1] || "";
615 warn "Closing \#$self->{fd} due to $pkg/$filename/$line ($reason)\n";
618 # this does most of the work of closing us
621 # defer closing the actual socket until the event loop is done
622 # processing this round of events. (otherwise we might reuse fds)
624 push @ToClose, $self->{sock};
625 $self->{sock} = undef;
631 ### METHOD: _cleanup()
632 ### Called by our closers so we can clean internal data structures.
634 my PublicInbox::DS $self = $_[0];
636 # we're effectively closed; we have no fd and sock when we leave here
639 # we need to flush our write buffer, as there may
640 # be self-referential closures (sub { $client->close })
641 # preventing the object from being destroyed
642 $self->{write_buf} = [];
644 # if we're using epoll, we have to remove this from our epoll fd so we stop getting
645 # notifications about it
646 if ($HaveEpoll && $self->{fd}) {
647 if (epoll_ctl($Epoll, EPOLL_CTL_DEL, $self->{fd}, $self->{event_watch}) != 0) {
648 # dump_error prints a backtrace so we can try to figure out why this happened
649 $self->dump_error("epoll_ctl(): failure deleting fd=$self->{fd} during _cleanup(); $! (" . ($!+0) . ")");
653 # now delete from mappings. this fd no longer belongs to us, so we don't want
654 # to get alerts for it if it becomes writable/readable/etc.
655 delete $PLCMap{$self->{fd}};
657 # we explicitly don't delete from DescriptorMap here until we
658 # actually close the socket, as we might be in the middle of
659 # processing an epoll_wait/etc that returned hundreds of fds, one
660 # of which is not yet processed and is what we're closing. if we
661 # keep it in DescriptorMap, then the event harnesses can just
662 # looked at $pob->{closed} and ignore it. but if it's an
663 # un-accounted for fd, then it (understandably) freak out a bit
664 # and emit warnings, thinking their state got off.
666 # and finally get rid of our fd so we can't use it anywhere else
670 =head2 C<< $obj->sock() >>
672 Returns the underlying IO::Handle for the object.
676 my PublicInbox::DS $self = shift;
677 return $self->{sock};
680 =head2 C<< $obj->set_writer_func( CODEREF ) >>
682 Sets a function to use instead of C<syswrite()> when writing data to the socket.
685 sub set_writer_func {
686 my PublicInbox::DS $self = shift;
688 Carp::croak("Not a subref") unless !defined $wtr || UNIVERSAL::isa($wtr, "CODE");
689 $self->{writer_func} = $wtr;
692 =head2 C<< $obj->write( $data ) >>
694 Write the specified data to the underlying handle. I<data> may be scalar,
695 scalar ref, code ref (to run when there), or undef just to kick-start.
696 Returns 1 if writes all went through, or 0 if there are writes in queue. If
697 it returns 1, caller should stop waiting for 'writable' events)
701 my PublicInbox::DS $self;
705 # nobody should be writing to closed sockets, but caller code can
706 # do two writes within an event, have the first fail and
707 # disconnect the other side (whose destructor then closes the
708 # calling object, but it's still in a method), and then the
709 # now-dead object does its second write. that is this case. we
710 # just lie and say it worked. it'll be dead soon and won't be
712 return 1 if $self->{closed};
716 # just queue data if there's already a wait
720 $bref = ref $data ? $data : \$data;
721 if ($self->{write_buf_size}) {
722 push @{$self->{write_buf}}, $bref;
723 $self->{write_buf_size} += ref $bref eq "SCALAR" ? length($$bref) : 1;
727 # this flag says we're bypassing the queue system, knowing we're the
728 # only outstanding write, and hoping we don't ever need to use it.
729 # if so later, though, we'll need to queue
735 return 1 unless $bref ||= $self->{write_buf}[0];
739 $len = length($$bref); # this will die if $bref is a code ref, caught below
742 if (UNIVERSAL::isa($bref, "CODE")) {
743 unless ($need_queue) {
744 $self->{write_buf_size}--; # code refs are worth 1
745 shift @{$self->{write_buf}};
749 # code refs are just run and never get reenqueued
750 # (they're one-shot), so turn off the flag indicating the
751 # outstanding data needs queueing.
757 die "Write error: $@ <$bref>";
760 my $to_write = $len - $self->{write_buf_offset};
762 if (my $wtr = $self->{writer_func}) {
763 $written = $wtr->($bref, $to_write, $self->{write_buf_offset});
765 $written = syswrite($self->{sock}, $$bref, $to_write, $self->{write_buf_offset});
768 if (! defined $written) {
770 return $self->close("EPIPE");
771 } elsif ($! == EAGAIN) {
772 # since connection has stuff to write, it should now be
773 # interested in pending writes:
775 push @{$self->{write_buf}}, $bref;
776 $self->{write_buf_size} += $len;
778 $self->{write_set_watch} = 1 unless $self->{event_watch} & POLLOUT;
779 $self->watch_write(1);
781 } elsif ($! == ECONNRESET) {
782 return $self->close("ECONNRESET");
785 DebugLevel >= 1 && $self->debugmsg("Closing connection ($self) due to write error: $!\n");
787 return $self->close("write_error");
788 } elsif ($written != $to_write) {
789 DebugLevel >= 2 && $self->debugmsg("Wrote PARTIAL %d bytes to %d",
790 $written, $self->{fd});
792 push @{$self->{write_buf}}, $bref;
793 $self->{write_buf_size} += $len;
795 # since connection has stuff to write, it should now be
796 # interested in pending writes:
797 $self->{write_buf_offset} += $written;
798 $self->{write_buf_size} -= $written;
799 $self->on_incomplete_write;
801 } elsif ($written == $to_write) {
802 DebugLevel >= 2 && $self->debugmsg("Wrote ALL %d bytes to %d (nq=%d)",
803 $written, $self->{fd}, $need_queue);
804 $self->{write_buf_offset} = 0;
806 if ($self->{write_set_watch}) {
807 $self->watch_write(0);
808 $self->{write_set_watch} = 0;
811 # this was our only write, so we can return immediately
812 # since we avoided incrementing the buffer size or
813 # putting it in the buffer. we also know there
814 # can't be anything else to write.
815 return 1 if $need_queue;
817 $self->{write_buf_size} -= $written;
818 shift @{$self->{write_buf}};
825 sub on_incomplete_write {
826 my PublicInbox::DS $self = shift;
827 $self->{write_set_watch} = 1 unless $self->{event_watch} & POLLOUT;
828 $self->watch_write(1);
831 =head2 C<< $obj->read( $bytecount ) >>
833 Read at most I<bytecount> bytes from the underlying handle; returns scalar
834 ref on read, or undef on connection closed.
838 my PublicInbox::DS $self = shift;
839 return if $self->{closed};
842 my $sock = $self->{sock};
844 # if this is too high, perl quits(!!). reports on mailing lists
845 # don't seem to point to a universal answer. 5MB worked for some,
846 # crashed for others. 1MB works for more people. let's go with 1MB
848 my $req_bytes = $bytes > 1048576 ? 1048576 : $bytes;
850 my $res = sysread($sock, $buf, $req_bytes, 0);
851 DebugLevel >= 2 && $self->debugmsg("sysread = %d; \$! = %d", $res, $!);
853 if (! $res && $! != EWOULDBLOCK) {
854 # catches 0=conn closed or undef=error
855 DebugLevel >= 2 && $self->debugmsg("Fd \#%d read hit the end of the road.", $self->{fd});
862 =head2 (VIRTUAL) C<< $obj->event_read() >>
864 Readable event handler. Concrete deriviatives of PublicInbox::DS should
865 provide an implementation of this. The default implementation will die if
869 sub event_read { die "Base class event_read called for $_[0]\n"; }
871 =head2 (VIRTUAL) C<< $obj->event_err() >>
873 Error event handler. Concrete deriviatives of PublicInbox::DS should
874 provide an implementation of this. The default implementation will die if
878 sub event_err { die "Base class event_err called for $_[0]\n"; }
880 =head2 (VIRTUAL) C<< $obj->event_hup() >>
882 'Hangup' event handler. Concrete deriviatives of PublicInbox::DS should
883 provide an implementation of this. The default implementation will die if
887 sub event_hup { die "Base class event_hup called for $_[0]\n"; }
889 =head2 C<< $obj->event_write() >>
891 Writable event handler. Concrete deriviatives of PublicInbox::DS may wish to
892 provide an implementation of this. The default implementation calls
893 C<write()> with an C<undef>.
901 =head2 C<< $obj->watch_read( $boolean ) >>
903 Turn 'readable' event notification on or off.
907 my PublicInbox::DS $self = shift;
908 return if $self->{closed} || !$self->{sock};
911 my $event = $self->{event_watch};
913 $event &= ~POLLIN if ! $val;
914 $event |= POLLIN if $val;
916 # If it changed, set it
917 if ($event != $self->{event_watch}) {
919 $KQueue->EV_SET($self->{fd}, IO::KQueue::EVFILT_READ(),
920 $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
923 epoll_ctl($Epoll, EPOLL_CTL_MOD, $self->{fd}, $event)
924 and $self->dump_error("couldn't modify epoll settings for $self->{fd} " .
925 "from $self->{event_watch} -> $event: $! (" . ($!+0) . ")");
927 $self->{event_watch} = $event;
931 =head2 C<< $obj->watch_write( $boolean ) >>
933 Turn 'writable' event notification on or off.
937 my PublicInbox::DS $self = shift;
938 return if $self->{closed} || !$self->{sock};
941 my $event = $self->{event_watch};
943 $event &= ~POLLOUT if ! $val;
944 $event |= POLLOUT if $val;
946 if ($val && caller ne __PACKAGE__) {
947 # A subclass registered interest, it's now responsible for this.
948 $self->{write_set_watch} = 0;
951 # If it changed, set it
952 if ($event != $self->{event_watch}) {
954 $KQueue->EV_SET($self->{fd}, IO::KQueue::EVFILT_WRITE(),
955 $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
958 epoll_ctl($Epoll, EPOLL_CTL_MOD, $self->{fd}, $event)
959 and $self->dump_error("couldn't modify epoll settings for $self->{fd} " .
960 "from $self->{event_watch} -> $event: $! (" . ($!+0) . ")");
962 $self->{event_watch} = $event;
966 =head2 C<< $obj->dump_error( $message ) >>
968 Prints to STDERR a backtrace with information about this socket and what lead
969 up to the dump_error call.
975 while (my ($file, $line, $sub) = (caller($i++))[1..3]) {
976 push @list, "\t$file:$line called $sub\n";
979 warn "ERROR: $_[1]\n" .
980 "\t$_[0] = " . $_[0]->as_string . "\n" .
984 =head2 C<< $obj->debugmsg( $format, @args ) >>
986 Print the debugging message specified by the C<sprintf>-style I<format> and
991 my ( $self, $fmt, @args ) = @_;
992 confess "Not an object" unless ref $self;
995 printf STDERR ">>> $fmt\n", @args;
998 =head2 C<< $obj->as_string() >>
1000 Returns a string describing this socket.
1004 my PublicInbox::DS $self = shift;
1005 my $rw = "(" . ($self->{event_watch} & POLLIN ? 'R' : '') .
1006 ($self->{event_watch} & POLLOUT ? 'W' : '') . ")";
1007 my $ret = ref($self) . "$rw: " . ($self->{closed} ? "closed" : "open");
1011 package PublicInbox::DS::Timer;
1012 # [$abs_float_firetime, $coderef];
1019 =head1 AUTHORS (Danga::Socket)
1021 Brad Fitzpatrick <brad@danga.com> - author
1023 Michael Granger <ged@danga.com> - docs, testing
1025 Mark Smith <junior@danga.com> - contributor, heavy user, testing
1027 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits