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";
336 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);
389 unless ($count >= 0) {
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 = eval { $KQueue->kevent($timeout) };
433 # workaround https://rt.cpan.org/Ticket/Display.html?id=116615
434 if ($err =~ /Interrupted system call/) {
441 foreach my $kev (@ret) {
442 my ($fd, $filter, $flags, $fflags) = @$kev;
443 my PublicInbox::DS $pob = $DescriptorMap{$fd};
445 if (my $code = $OtherFds{$fd}) {
448 warn "kevent() returned fd $fd for which we have no mapping. removing.\n";
449 POSIX::close($fd); # close deletes the kevent entry
454 DebugLevel >= 1 && $class->DebugMsg("Event: fd=%d (%s), flags=%d \@ %s\n",
455 $fd, ref($pob), $flags, time);
457 $pob->event_read if $filter == IO::KQueue::EVFILT_READ() && !$pob->{closed};
458 $pob->event_write if $filter == IO::KQueue::EVFILT_WRITE() && !$pob->{closed};
459 if ($flags == IO::KQueue::EV_EOF() && !$pob->{closed}) {
467 return unless PostEventLoop();
473 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
475 Sets post loop callback function. Pass a subref and it will be
476 called every time the event loop finishes.
478 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
481 The callback function will be passed two parameters: \%DescriptorMap, \%OtherFds.
484 sub SetPostLoopCallback {
485 my ($class, $ref) = @_;
488 # per-object callback
489 my PublicInbox::DS $self = $class;
490 if (defined $ref && ref $ref eq 'CODE') {
491 $PLCMap{$self->{fd}} = $ref;
493 delete $PLCMap{$self->{fd}};
497 $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
501 # Internal function: run the post-event callback, send read events
502 # for pushed-back data, and close pending connections. returns 1
503 # if event loop should continue, or 0 to shut it all down.
505 # now we can close sockets that wanted to close during our event processing.
506 # (we didn't want to close them during the loop, as we didn't want fd numbers
507 # being reused and confused during the event loop)
508 while (my $sock = shift @ToClose) {
509 my $fd = fileno($sock);
511 # close the socket. (not a PublicInbox::DS close)
514 # and now we can finally remove the fd from the map. see
515 # comment above in _cleanup.
516 delete $DescriptorMap{$fd};
520 # by default we keep running, unless a postloop callback (either per-object
521 # or global) cancels it
522 my $keep_running = 1;
524 # per-object post-loop-callbacks
525 for my $plc (values %PLCMap) {
526 $keep_running &&= $plc->(\%DescriptorMap, \%OtherFds);
529 # now we're at the very end, call callback if defined
530 if (defined $PostLoopCallback) {
531 $keep_running &&= $PostLoopCallback->(\%DescriptorMap, \%OtherFds);
534 return $keep_running;
537 #####################################################################
538 ### PublicInbox::DS-the-object code
539 #####################################################################
541 =head2 OBJECT METHODS
543 =head2 C<< CLASS->new( $socket ) >>
545 Create a new PublicInbox::DS subclass object for the given I<socket> which will
546 react to events on it during the C<EventLoop>.
548 This is normally (always?) called from your subclass via:
550 $class->SUPER::new($socket);
554 my ($self, $sock, $exclusive) = @_;
555 $self = fields::new($self) unless ref $self;
557 $self->{sock} = $sock;
558 my $fd = fileno($sock);
560 Carp::cluck("undef sock and/or fd in PublicInbox::DS->new. sock=" . ($sock || "") . ", fd=" . ($fd || ""))
564 $self->{write_buf} = [];
565 $self->{write_buf_offset} = 0;
566 $self->{write_buf_size} = 0;
569 my $ev = $self->{event_watch} = POLLERR|POLLHUP|POLLNVAL;
575 $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP|$EPOLLEXCLUSIVE;
578 if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
579 if ($!{EINVAL} && ($ev & $EPOLLEXCLUSIVE)) {
580 $EPOLLEXCLUSIVE = 0; # old kernel
581 $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP;
584 die "couldn't add epoll watch for $fd: $!\n";
587 elsif ($HaveKQueue) {
588 # Add them to the queue but disabled for now
589 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(),
590 IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
591 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_WRITE(),
592 IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
595 Carp::cluck("PublicInbox::DS::new blowing away existing descriptor map for fd=$fd ($DescriptorMap{$fd})")
596 if $DescriptorMap{$fd};
598 $DescriptorMap{$fd} = $self;
603 #####################################################################
604 ### I N S T A N C E M E T H O D S
605 #####################################################################
607 =head2 C<< $obj->steal_socket() >>
609 Basically returns our socket and makes it so that we don't try to close it,
610 but we do remove it from epoll handlers. THIS CLOSES $self. It is the same
611 thing as calling close, except it gives you the socket to use.
615 my PublicInbox::DS $self = $_[0];
616 return if $self->{closed};
618 # cleanup does most of the work of closing this socket
621 # now undef our internal sock and fd structures so we don't use them
622 my $sock = $self->{sock};
623 $self->{sock} = undef;
627 =head2 C<< $obj->close( [$reason] ) >>
629 Close the socket. The I<reason> argument will be used in debugging messages.
633 my PublicInbox::DS $self = $_[0];
634 return if $self->{closed};
636 # print out debugging info for this close
638 my ($pkg, $filename, $line) = caller;
639 my $reason = $_[1] || "";
640 warn "Closing \#$self->{fd} due to $pkg/$filename/$line ($reason)\n";
643 # this does most of the work of closing us
646 # defer closing the actual socket until the event loop is done
647 # processing this round of events. (otherwise we might reuse fds)
649 push @ToClose, $self->{sock};
650 $self->{sock} = undef;
656 ### METHOD: _cleanup()
657 ### Called by our closers so we can clean internal data structures.
659 my PublicInbox::DS $self = $_[0];
661 # we're effectively closed; we have no fd and sock when we leave here
664 # we need to flush our write buffer, as there may
665 # be self-referential closures (sub { $client->close })
666 # preventing the object from being destroyed
667 $self->{write_buf} = [];
669 # if we're using epoll, we have to remove this from our epoll fd so we stop getting
670 # notifications about it
671 if ($HaveEpoll && $self->{fd}) {
672 if (epoll_ctl($Epoll, EPOLL_CTL_DEL, $self->{fd}, $self->{event_watch}) != 0) {
673 # dump_error prints a backtrace so we can try to figure out why this happened
674 $self->dump_error("epoll_ctl(): failure deleting fd=$self->{fd} during _cleanup(); $! (" . ($!+0) . ")");
678 # now delete from mappings. this fd no longer belongs to us, so we don't want
679 # to get alerts for it if it becomes writable/readable/etc.
680 delete $PLCMap{$self->{fd}};
682 # we explicitly don't delete from DescriptorMap here until we
683 # actually close the socket, as we might be in the middle of
684 # processing an epoll_wait/etc that returned hundreds of fds, one
685 # of which is not yet processed and is what we're closing. if we
686 # keep it in DescriptorMap, then the event harnesses can just
687 # looked at $pob->{closed} and ignore it. but if it's an
688 # un-accounted for fd, then it (understandably) freak out a bit
689 # and emit warnings, thinking their state got off.
691 # and finally get rid of our fd so we can't use it anywhere else
695 =head2 C<< $obj->sock() >>
697 Returns the underlying IO::Handle for the object.
701 my PublicInbox::DS $self = shift;
702 return $self->{sock};
705 =head2 C<< $obj->set_writer_func( CODEREF ) >>
707 Sets a function to use instead of C<syswrite()> when writing data to the socket.
710 sub set_writer_func {
711 my PublicInbox::DS $self = shift;
713 Carp::croak("Not a subref") unless !defined $wtr || UNIVERSAL::isa($wtr, "CODE");
714 $self->{writer_func} = $wtr;
717 =head2 C<< $obj->write( $data ) >>
719 Write the specified data to the underlying handle. I<data> may be scalar,
720 scalar ref, code ref (to run when there), or undef just to kick-start.
721 Returns 1 if writes all went through, or 0 if there are writes in queue. If
722 it returns 1, caller should stop waiting for 'writable' events)
726 my PublicInbox::DS $self;
730 # nobody should be writing to closed sockets, but caller code can
731 # do two writes within an event, have the first fail and
732 # disconnect the other side (whose destructor then closes the
733 # calling object, but it's still in a method), and then the
734 # now-dead object does its second write. that is this case. we
735 # just lie and say it worked. it'll be dead soon and won't be
737 return 1 if $self->{closed};
741 # just queue data if there's already a wait
745 $bref = ref $data ? $data : \$data;
746 if ($self->{write_buf_size}) {
747 push @{$self->{write_buf}}, $bref;
748 $self->{write_buf_size} += ref $bref eq "SCALAR" ? length($$bref) : 1;
752 # this flag says we're bypassing the queue system, knowing we're the
753 # only outstanding write, and hoping we don't ever need to use it.
754 # if so later, though, we'll need to queue
760 return 1 unless $bref ||= $self->{write_buf}[0];
764 $len = length($$bref); # this will die if $bref is a code ref, caught below
767 if (UNIVERSAL::isa($bref, "CODE")) {
768 unless ($need_queue) {
769 $self->{write_buf_size}--; # code refs are worth 1
770 shift @{$self->{write_buf}};
774 # code refs are just run and never get reenqueued
775 # (they're one-shot), so turn off the flag indicating the
776 # outstanding data needs queueing.
782 die "Write error: $@ <$bref>";
785 my $to_write = $len - $self->{write_buf_offset};
787 if (my $wtr = $self->{writer_func}) {
788 $written = $wtr->($bref, $to_write, $self->{write_buf_offset});
790 $written = syswrite($self->{sock}, $$bref, $to_write, $self->{write_buf_offset});
793 if (! defined $written) {
795 return $self->close("EPIPE");
796 } elsif ($! == EAGAIN) {
797 # since connection has stuff to write, it should now be
798 # interested in pending writes:
800 push @{$self->{write_buf}}, $bref;
801 $self->{write_buf_size} += $len;
803 $self->{write_set_watch} = 1 unless $self->{event_watch} & POLLOUT;
804 $self->watch_write(1);
806 } elsif ($! == ECONNRESET) {
807 return $self->close("ECONNRESET");
810 DebugLevel >= 1 && $self->debugmsg("Closing connection ($self) due to write error: $!\n");
812 return $self->close("write_error");
813 } elsif ($written != $to_write) {
814 DebugLevel >= 2 && $self->debugmsg("Wrote PARTIAL %d bytes to %d",
815 $written, $self->{fd});
817 push @{$self->{write_buf}}, $bref;
818 $self->{write_buf_size} += $len;
820 # since connection has stuff to write, it should now be
821 # interested in pending writes:
822 $self->{write_buf_offset} += $written;
823 $self->{write_buf_size} -= $written;
824 $self->on_incomplete_write;
826 } elsif ($written == $to_write) {
827 DebugLevel >= 2 && $self->debugmsg("Wrote ALL %d bytes to %d (nq=%d)",
828 $written, $self->{fd}, $need_queue);
829 $self->{write_buf_offset} = 0;
831 if ($self->{write_set_watch}) {
832 $self->watch_write(0);
833 $self->{write_set_watch} = 0;
836 # this was our only write, so we can return immediately
837 # since we avoided incrementing the buffer size or
838 # putting it in the buffer. we also know there
839 # can't be anything else to write.
840 return 1 if $need_queue;
842 $self->{write_buf_size} -= $written;
843 shift @{$self->{write_buf}};
850 sub on_incomplete_write {
851 my PublicInbox::DS $self = shift;
852 $self->{write_set_watch} = 1 unless $self->{event_watch} & POLLOUT;
853 $self->watch_write(1);
856 =head2 C<< $obj->read( $bytecount ) >>
858 Read at most I<bytecount> bytes from the underlying handle; returns scalar
859 ref on read, or undef on connection closed.
863 my PublicInbox::DS $self = shift;
864 return if $self->{closed};
867 my $sock = $self->{sock};
869 # if this is too high, perl quits(!!). reports on mailing lists
870 # don't seem to point to a universal answer. 5MB worked for some,
871 # crashed for others. 1MB works for more people. let's go with 1MB
873 my $req_bytes = $bytes > 1048576 ? 1048576 : $bytes;
875 my $res = sysread($sock, $buf, $req_bytes, 0);
876 DebugLevel >= 2 && $self->debugmsg("sysread = %d; \$! = %d", $res, $!);
878 if (! $res && $! != EWOULDBLOCK) {
879 # catches 0=conn closed or undef=error
880 DebugLevel >= 2 && $self->debugmsg("Fd \#%d read hit the end of the road.", $self->{fd});
887 =head2 (VIRTUAL) C<< $obj->event_read() >>
889 Readable event handler. Concrete deriviatives of PublicInbox::DS should
890 provide an implementation of this. The default implementation will die if
894 sub event_read { die "Base class event_read called for $_[0]\n"; }
896 =head2 (VIRTUAL) C<< $obj->event_err() >>
898 Error event handler. Concrete deriviatives of PublicInbox::DS should
899 provide an implementation of this. The default implementation will die if
903 sub event_err { die "Base class event_err called for $_[0]\n"; }
905 =head2 (VIRTUAL) C<< $obj->event_hup() >>
907 'Hangup' event handler. Concrete deriviatives of PublicInbox::DS should
908 provide an implementation of this. The default implementation will die if
912 sub event_hup { die "Base class event_hup called for $_[0]\n"; }
914 =head2 C<< $obj->event_write() >>
916 Writable event handler. Concrete deriviatives of PublicInbox::DS may wish to
917 provide an implementation of this. The default implementation calls
918 C<write()> with an C<undef>.
926 =head2 C<< $obj->watch_read( $boolean ) >>
928 Turn 'readable' event notification on or off.
932 my PublicInbox::DS $self = shift;
933 return if $self->{closed} || !$self->{sock};
936 my $event = $self->{event_watch};
938 $event &= ~POLLIN if ! $val;
939 $event |= POLLIN if $val;
941 # If it changed, set it
942 if ($event != $self->{event_watch}) {
944 $KQueue->EV_SET($self->{fd}, IO::KQueue::EVFILT_READ(),
945 $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
948 epoll_ctl($Epoll, EPOLL_CTL_MOD, $self->{fd}, $event)
949 and $self->dump_error("couldn't modify epoll settings for $self->{fd} " .
950 "from $self->{event_watch} -> $event: $! (" . ($!+0) . ")");
952 $self->{event_watch} = $event;
956 =head2 C<< $obj->watch_write( $boolean ) >>
958 Turn 'writable' event notification on or off.
962 my PublicInbox::DS $self = shift;
963 return if $self->{closed} || !$self->{sock};
966 my $event = $self->{event_watch};
968 $event &= ~POLLOUT if ! $val;
969 $event |= POLLOUT if $val;
971 if ($val && caller ne __PACKAGE__) {
972 # A subclass registered interest, it's now responsible for this.
973 $self->{write_set_watch} = 0;
976 # If it changed, set it
977 if ($event != $self->{event_watch}) {
979 $KQueue->EV_SET($self->{fd}, IO::KQueue::EVFILT_WRITE(),
980 $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
983 epoll_ctl($Epoll, EPOLL_CTL_MOD, $self->{fd}, $event)
984 and $self->dump_error("couldn't modify epoll settings for $self->{fd} " .
985 "from $self->{event_watch} -> $event: $! (" . ($!+0) . ")");
987 $self->{event_watch} = $event;
991 =head2 C<< $obj->dump_error( $message ) >>
993 Prints to STDERR a backtrace with information about this socket and what lead
994 up to the dump_error call.
1000 while (my ($file, $line, $sub) = (caller($i++))[1..3]) {
1001 push @list, "\t$file:$line called $sub\n";
1004 warn "ERROR: $_[1]\n" .
1005 "\t$_[0] = " . $_[0]->as_string . "\n" .
1009 =head2 C<< $obj->debugmsg( $format, @args ) >>
1011 Print the debugging message specified by the C<sprintf>-style I<format> and
1016 my ( $self, $fmt, @args ) = @_;
1017 confess "Not an object" unless ref $self;
1020 printf STDERR ">>> $fmt\n", @args;
1023 =head2 C<< $obj->as_string() >>
1025 Returns a string describing this socket.
1029 my PublicInbox::DS $self = shift;
1030 my $rw = "(" . ($self->{event_watch} & POLLIN ? 'R' : '') .
1031 ($self->{event_watch} & POLLOUT ? 'W' : '') . ")";
1032 my $ret = ref($self) . "$rw: " . ($self->{closed} ? "closed" : "open");
1036 package PublicInbox::DS::Timer;
1037 # [$abs_float_firetime, $coderef];
1044 =head1 AUTHORS (Danga::Socket)
1046 Brad Fitzpatrick <brad@danga.com> - author
1048 Michael Granger <ged@danga.com> - docs, testing
1050 Mark Smith <junior@danga.com> - contributor, heavy user, testing
1052 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits