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 my $opt_bsd_resource = eval "use BSD::Resource; 1;";
18 use vars qw{$VERSION};
22 no warnings qw(deprecated);
24 use PublicInbox::Syscall qw(:epoll);
26 use fields ('sock', # underlying socket
27 'fd', # numeric file descriptor
28 'write_buf', # arrayref of scalars, scalarrefs, or coderefs to write
29 'write_buf_offset', # offset into first array of write_buf to start writing at
30 'write_buf_size', # total length of data in all write_buf items
31 'write_set_watch', # bool: true if we internally set watch_write rather than by a subclass
32 'closed', # bool: socket is closed
33 'event_watch', # bitmask of events the client is interested in (POLLIN,OUT,etc.)
34 'writer_func', # subref which does writing. must return bytes written (or undef) and set $! on errors
37 use Errno qw(EINPROGRESS EWOULDBLOCK EISCONN ENOTSOCK
38 EPIPE EAGAIN EBADF ECONNRESET ENOPROTOOPT);
39 use Socket qw(IPPROTO_TCP);
40 use Carp qw(croak confess);
42 use constant DebugLevel => 0;
44 use constant POLLIN => 1;
45 use constant POLLOUT => 4;
46 use constant POLLERR => 8;
47 use constant POLLHUP => 16;
48 use constant POLLNVAL => 32;
50 our $HAVE_KQUEUE = eval { require IO::KQueue; 1 };
53 $HaveEpoll, # Flag -- is epoll available? initially undefined.
55 %DescriptorMap, # fd (num) -> PublicInbox::DS object
56 $Epoll, # Global epoll fd (for epoll mode only)
57 $KQueue, # Global kqueue fd (for kqueue mode only)
58 @ToClose, # sockets to close when event loop is done
59 %OtherFds, # A hash of "other" (non-PublicInbox::DS) file
60 # descriptors for the event loop to track.
62 $PostLoopCallback, # subref to call at the end of each loop, if defined (global)
63 %PLCMap, # fd (num) -> PostLoopCallback (per-object)
65 $LoopTimeout, # timeout of event loop in milliseconds
66 $DoProfile, # if on, enable profiling
67 %Profiling, # what => [ utime, stime, calls ]
68 $DoneInit, # if we've done the one-time module init yet
72 # this may be set to zero with old kernels
73 our $EPOLLEXCLUSIVE = EPOLLEXCLUSIVE;
76 #####################################################################
77 ### C L A S S M E T H O D S
78 #####################################################################
80 =head2 C<< CLASS->Reset() >>
89 $LoopTimeout = -1; # no timeout by default
94 $PostLoopCallback = undef;
98 POSIX::close($Epoll) if defined $Epoll && $Epoll >= 0;
99 POSIX::close($KQueue) if defined $KQueue && $KQueue >= 0;
101 *EventLoop = *FirstTimeEventLoop;
104 =head2 C<< CLASS->HaveEpoll() >>
106 Returns a true value if this class will use IO::Epoll for async IO.
114 =head2 C<< CLASS->WatchedSockets() >>
116 Returns the number of file descriptors which are registered with the global
121 return scalar keys %DescriptorMap;
123 *watched_sockets = *WatchedSockets;
125 =head2 C<< CLASS->EnableProfiling() >>
127 Turns profiling on, clearing current profiling data.
130 sub EnableProfiling {
131 if ($opt_bsd_resource) {
139 =head2 C<< CLASS->DisableProfiling() >>
141 Turns off profiling, but retains data up to this point
144 sub DisableProfiling {
148 =head2 C<< CLASS->ProfilingData() >>
150 Returns reference to a hash of data in format:
152 ITEM => [ utime, stime, #calls ]
159 =head2 C<< CLASS->ToClose() >>
161 Return the list of sockets that are awaiting close() at the end of the
165 sub ToClose { return @ToClose; }
167 =head2 C<< CLASS->OtherFds( [%fdmap] ) >>
169 Get/set the hash of file descriptors that need processing in parallel with
170 the registered PublicInbox::DS objects.
175 if ( @_ ) { %OtherFds = @_ }
176 return wantarray ? %OtherFds : \%OtherFds;
179 =head2 C<< CLASS->AddOtherFds( [%fdmap] ) >>
181 Add fds to the OtherFds hash for processing.
186 %OtherFds = ( %OtherFds, @_ ); # FIXME investigate what happens on dupe fds
187 return wantarray ? %OtherFds : \%OtherFds;
190 =head2 C<< CLASS->SetLoopTimeout( $timeout ) >>
192 Set the loop timeout for the event loop to some value in milliseconds.
194 A timeout of 0 (zero) means poll forever. A timeout of -1 means poll and return
199 return $LoopTimeout = $_[1] + 0;
202 =head2 C<< CLASS->DebugMsg( $format, @args ) >>
204 Print the debugging message specified by the C<sprintf>-style I<format> and
209 my ( $class, $fmt, @args ) = @_;
211 printf STDERR ">>> $fmt\n", @args;
214 =head2 C<< CLASS->AddTimer( $seconds, $coderef ) >>
216 Add a timer to occur $seconds from now. $seconds may be fractional, but timers
217 are not guaranteed to fire at the exact time you ask for.
219 Returns a timer object which you can call C<< $timer->cancel >> on if you need to.
224 my ($secs, $coderef) = @_;
226 my $fire_time = Time::HiRes::time() + $secs;
228 my $timer = bless [$fire_time, $coderef], "PublicInbox::DS::Timer";
230 if (!@Timers || $fire_time >= $Timers[-1][0]) {
231 push @Timers, $timer;
235 # Now, where do we insert? (NOTE: this appears slow, algorithm-wise,
236 # but it was compared against calendar queues, heaps, naive push/sort,
237 # and a bunch of other versions, and found to be fastest with a large
238 # variety of datasets.)
239 for (my $i = 0; $i < @Timers; $i++) {
240 if ($Timers[$i][0] > $fire_time) {
241 splice(@Timers, $i, 0, $timer);
246 die "Shouldn't get here.";
249 =head2 C<< CLASS->DescriptorMap() >>
251 Get the hash of PublicInbox::DS objects keyed by the file descriptor (fileno) they
254 Returns a hash in list context or a hashref in scalar context.
258 return wantarray ? %DescriptorMap : \%DescriptorMap;
260 *descriptor_map = *DescriptorMap;
261 *get_sock_ref = *DescriptorMap;
269 $KQueue = IO::KQueue->new();
270 $HaveKQueue = $KQueue >= 0;
272 *EventLoop = *KQueueEventLoop;
275 elsif (PublicInbox::Syscall::epoll_defined()) {
276 $Epoll = eval { epoll_create(1024); };
277 $HaveEpoll = defined $Epoll && $Epoll >= 0;
279 *EventLoop = *EpollEventLoop;
283 if (!$HaveEpoll && !$HaveKQueue) {
285 *EventLoop = *PollEventLoop;
289 =head2 C<< CLASS->EventLoop() >>
291 Start processing IO events. In most daemon programs this never exits. See
292 C<PostLoopCallback> below for how to exit the loop.
295 sub FirstTimeEventLoop {
301 EpollEventLoop($class);
302 } elsif ($HaveKQueue) {
303 KQueueEventLoop($class);
305 PollEventLoop($class);
309 ## profiling-related data/functions
310 our ($Prof_utime0, $Prof_stime0);
312 ($Prof_utime0, $Prof_stime0) = getrusage();
316 # get post information
317 my ($autime, $astime) = getrusage();
319 # calculate differences
320 my $utime = $autime - $Prof_utime0;
321 my $stime = $astime - $Prof_stime0;
324 $Profiling{$k} ||= [ 0.0, 0.0, 0 ];
325 $Profiling{$k}->[0] += $utime;
326 $Profiling{$k}->[1] += $stime;
327 $Profiling{$k}->[2]++;
331 # runs timers and returns milliseconds for next one, or next event loop
333 return $LoopTimeout unless @Timers;
335 my $now = Time::HiRes::time();
338 while (@Timers && $Timers[0][0] <= $now) {
339 my $to_run = shift(@Timers);
340 $to_run->[1]->($now) if $to_run->[1];
343 return $LoopTimeout unless @Timers;
345 # convert time to an even number of milliseconds, adding 1
346 # extra, otherwise floating point fun can occur and we'll
347 # call RunTimers like 20-30 times, each returning a timeout
348 # of 0.0000212 seconds
349 my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
351 # -1 is an infinite timeout, so prefer a real timeout
352 return $timeout if $LoopTimeout == -1;
354 # otherwise pick the lower of our regular timeout and time until
356 return $LoopTimeout if $LoopTimeout < $timeout;
360 ### The epoll-based event loop. Gets installed as EventLoop if IO::Epoll loads
365 foreach my $fd ( keys %OtherFds ) {
366 if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, EPOLLIN) == -1) {
367 warn "epoll_ctl(): failure adding fd=$fd; $! (", $!+0, ")\n";
374 my $timeout = RunTimers();
376 # get up to 1000 events
377 my $evcount = epoll_wait($Epoll, 1000, $timeout, \@events);
379 for ($i=0; $i<$evcount; $i++) {
380 my $ev = $events[$i];
382 # it's possible epoll_wait returned many events, including some at the end
383 # that ones in the front triggered unregister-interest actions. if we
384 # can't find the %sock entry, it's because we're no longer interested
386 my PublicInbox::DS $pob = $DescriptorMap{$ev->[0]};
388 my $state = $ev->[1];
390 # if we didn't find a Perlbal::Socket subclass for that fd, try other
391 # pseudo-registered (above) fds.
393 if (my $code = $OtherFds{$ev->[0]}) {
397 warn "epoll() returned fd $fd w/ state $state for which we have no mapping. removing.\n";
399 epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, 0);
404 DebugLevel >= 1 && $class->DebugMsg("Event: fd=%d (%s), state=%d \@ %s\n",
405 $ev->[0], ref($pob), $ev->[1], time);
408 my $class = ref $pob;
410 # call profiling action on things that need to be done
411 if ($state & EPOLLIN && ! $pob->{closed}) {
414 _post_profile("$class-read");
417 if ($state & EPOLLOUT && ! $pob->{closed}) {
420 _post_profile("$class-write");
423 if ($state & (EPOLLERR|EPOLLHUP)) {
424 if ($state & EPOLLERR && ! $pob->{closed}) {
427 _post_profile("$class-err");
429 if ($state & EPOLLHUP && ! $pob->{closed}) {
432 _post_profile("$class-hup");
439 # standard non-profiling codepat
440 $pob->event_read if $state & EPOLLIN && ! $pob->{closed};
441 $pob->event_write if $state & EPOLLOUT && ! $pob->{closed};
442 if ($state & (EPOLLERR|EPOLLHUP)) {
443 $pob->event_err if $state & EPOLLERR && ! $pob->{closed};
444 $pob->event_hup if $state & EPOLLHUP && ! $pob->{closed};
447 return unless PostEventLoop();
452 ### The fallback IO::Poll-based event loop. Gets installed as EventLoop if
453 ### IO::Epoll fails to load.
457 my PublicInbox::DS $pob;
460 my $timeout = RunTimers();
462 # the following sets up @poll as a series of ($poll,$event_mask)
463 # items, then uses IO::Poll::_poll, implemented in XS, which
464 # modifies the array in place with the even elements being
465 # replaced with the event masks that occured.
467 foreach my $fd ( keys %OtherFds ) {
468 push @poll, $fd, POLLIN;
470 while ( my ($fd, $sock) = each %DescriptorMap ) {
471 push @poll, $fd, $sock->{event_watch};
474 # if nothing to poll, either end immediately (if no timeout)
475 # or just keep calling the callback
477 select undef, undef, undef, ($timeout / 1000);
478 return unless PostEventLoop();
482 my $count = IO::Poll::_poll($timeout, @poll);
484 return unless PostEventLoop();
488 # Fetch handles with read events
490 my ($fd, $state) = splice(@poll, 0, 2);
493 $pob = $DescriptorMap{$fd};
496 if (my $code = $OtherFds{$fd}) {
502 $pob->event_read if $state & POLLIN && ! $pob->{closed};
503 $pob->event_write if $state & POLLOUT && ! $pob->{closed};
504 $pob->event_err if $state & POLLERR && ! $pob->{closed};
505 $pob->event_hup if $state & POLLHUP && ! $pob->{closed};
508 return unless PostEventLoop();
514 ### The kqueue-based event loop. Gets installed as EventLoop if IO::KQueue works
516 sub KQueueEventLoop {
519 foreach my $fd (keys %OtherFds) {
520 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(), IO::KQueue::EV_ADD());
524 my $timeout = RunTimers();
525 my @ret = $KQueue->kevent($timeout);
527 foreach my $kev (@ret) {
528 my ($fd, $filter, $flags, $fflags) = @$kev;
529 my PublicInbox::DS $pob = $DescriptorMap{$fd};
531 if (my $code = $OtherFds{$fd}) {
534 warn "kevent() returned fd $fd for which we have no mapping. removing.\n";
535 POSIX::close($fd); # close deletes the kevent entry
540 DebugLevel >= 1 && $class->DebugMsg("Event: fd=%d (%s), flags=%d \@ %s\n",
541 $fd, ref($pob), $flags, time);
543 $pob->event_read if $filter == IO::KQueue::EVFILT_READ() && !$pob->{closed};
544 $pob->event_write if $filter == IO::KQueue::EVFILT_WRITE() && !$pob->{closed};
545 if ($flags == IO::KQueue::EV_EOF() && !$pob->{closed}) {
553 return unless PostEventLoop();
559 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
561 Sets post loop callback function. Pass a subref and it will be
562 called every time the event loop finishes.
564 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
567 The callback function will be passed two parameters: \%DescriptorMap, \%OtherFds.
570 sub SetPostLoopCallback {
571 my ($class, $ref) = @_;
574 # per-object callback
575 my PublicInbox::DS $self = $class;
576 if (defined $ref && ref $ref eq 'CODE') {
577 $PLCMap{$self->{fd}} = $ref;
579 delete $PLCMap{$self->{fd}};
583 $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
587 # Internal function: run the post-event callback, send read events
588 # for pushed-back data, and close pending connections. returns 1
589 # if event loop should continue, or 0 to shut it all down.
591 # now we can close sockets that wanted to close during our event processing.
592 # (we didn't want to close them during the loop, as we didn't want fd numbers
593 # being reused and confused during the event loop)
594 while (my $sock = shift @ToClose) {
595 my $fd = fileno($sock);
597 # close the socket. (not a PublicInbox::DS close)
600 # and now we can finally remove the fd from the map. see
601 # comment above in _cleanup.
602 delete $DescriptorMap{$fd};
606 # by default we keep running, unless a postloop callback (either per-object
607 # or global) cancels it
608 my $keep_running = 1;
610 # per-object post-loop-callbacks
611 for my $plc (values %PLCMap) {
612 $keep_running &&= $plc->(\%DescriptorMap, \%OtherFds);
615 # now we're at the very end, call callback if defined
616 if (defined $PostLoopCallback) {
617 $keep_running &&= $PostLoopCallback->(\%DescriptorMap, \%OtherFds);
620 return $keep_running;
623 #####################################################################
624 ### PublicInbox::DS-the-object code
625 #####################################################################
627 =head2 OBJECT METHODS
629 =head2 C<< CLASS->new( $socket ) >>
631 Create a new PublicInbox::DS subclass object for the given I<socket> which will
632 react to events on it during the C<EventLoop>.
634 This is normally (always?) called from your subclass via:
636 $class->SUPER::new($socket);
640 my ($self, $sock, $exclusive) = @_;
641 $self = fields::new($self) unless ref $self;
643 $self->{sock} = $sock;
644 my $fd = fileno($sock);
646 Carp::cluck("undef sock and/or fd in PublicInbox::DS->new. sock=" . ($sock || "") . ", fd=" . ($fd || ""))
650 $self->{write_buf} = [];
651 $self->{write_buf_offset} = 0;
652 $self->{write_buf_size} = 0;
655 my $ev = $self->{event_watch} = POLLERR|POLLHUP|POLLNVAL;
661 $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP|$EPOLLEXCLUSIVE;
664 if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
665 if ($!{EINVAL} && ($ev & $EPOLLEXCLUSIVE)) {
666 $EPOLLEXCLUSIVE = 0; # old kernel
667 $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP;
670 die "couldn't add epoll watch for $fd: $!\n";
673 elsif ($HaveKQueue) {
674 # Add them to the queue but disabled for now
675 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(),
676 IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
677 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_WRITE(),
678 IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
681 Carp::cluck("PublicInbox::DS::new blowing away existing descriptor map for fd=$fd ($DescriptorMap{$fd})")
682 if $DescriptorMap{$fd};
684 $DescriptorMap{$fd} = $self;
689 #####################################################################
690 ### I N S T A N C E M E T H O D S
691 #####################################################################
693 =head2 C<< $obj->steal_socket() >>
695 Basically returns our socket and makes it so that we don't try to close it,
696 but we do remove it from epoll handlers. THIS CLOSES $self. It is the same
697 thing as calling close, except it gives you the socket to use.
701 my PublicInbox::DS $self = $_[0];
702 return if $self->{closed};
704 # cleanup does most of the work of closing this socket
707 # now undef our internal sock and fd structures so we don't use them
708 my $sock = $self->{sock};
709 $self->{sock} = undef;
713 =head2 C<< $obj->close( [$reason] ) >>
715 Close the socket. The I<reason> argument will be used in debugging messages.
719 my PublicInbox::DS $self = $_[0];
720 return if $self->{closed};
722 # print out debugging info for this close
724 my ($pkg, $filename, $line) = caller;
725 my $reason = $_[1] || "";
726 warn "Closing \#$self->{fd} due to $pkg/$filename/$line ($reason)\n";
729 # this does most of the work of closing us
732 # defer closing the actual socket until the event loop is done
733 # processing this round of events. (otherwise we might reuse fds)
735 push @ToClose, $self->{sock};
736 $self->{sock} = undef;
742 ### METHOD: _cleanup()
743 ### Called by our closers so we can clean internal data structures.
745 my PublicInbox::DS $self = $_[0];
747 # we're effectively closed; we have no fd and sock when we leave here
750 # we need to flush our write buffer, as there may
751 # be self-referential closures (sub { $client->close })
752 # preventing the object from being destroyed
753 $self->{write_buf} = [];
755 # if we're using epoll, we have to remove this from our epoll fd so we stop getting
756 # notifications about it
757 if ($HaveEpoll && $self->{fd}) {
758 if (epoll_ctl($Epoll, EPOLL_CTL_DEL, $self->{fd}, $self->{event_watch}) != 0) {
759 # dump_error prints a backtrace so we can try to figure out why this happened
760 $self->dump_error("epoll_ctl(): failure deleting fd=$self->{fd} during _cleanup(); $! (" . ($!+0) . ")");
764 # now delete from mappings. this fd no longer belongs to us, so we don't want
765 # to get alerts for it if it becomes writable/readable/etc.
766 delete $PLCMap{$self->{fd}};
768 # we explicitly don't delete from DescriptorMap here until we
769 # actually close the socket, as we might be in the middle of
770 # processing an epoll_wait/etc that returned hundreds of fds, one
771 # of which is not yet processed and is what we're closing. if we
772 # keep it in DescriptorMap, then the event harnesses can just
773 # looked at $pob->{closed} and ignore it. but if it's an
774 # un-accounted for fd, then it (understandably) freak out a bit
775 # and emit warnings, thinking their state got off.
777 # and finally get rid of our fd so we can't use it anywhere else
781 =head2 C<< $obj->sock() >>
783 Returns the underlying IO::Handle for the object.
787 my PublicInbox::DS $self = shift;
788 return $self->{sock};
791 =head2 C<< $obj->set_writer_func( CODEREF ) >>
793 Sets a function to use instead of C<syswrite()> when writing data to the socket.
796 sub set_writer_func {
797 my PublicInbox::DS $self = shift;
799 Carp::croak("Not a subref") unless !defined $wtr || UNIVERSAL::isa($wtr, "CODE");
800 $self->{writer_func} = $wtr;
803 =head2 C<< $obj->write( $data ) >>
805 Write the specified data to the underlying handle. I<data> may be scalar,
806 scalar ref, code ref (to run when there), or undef just to kick-start.
807 Returns 1 if writes all went through, or 0 if there are writes in queue. If
808 it returns 1, caller should stop waiting for 'writable' events)
812 my PublicInbox::DS $self;
816 # nobody should be writing to closed sockets, but caller code can
817 # do two writes within an event, have the first fail and
818 # disconnect the other side (whose destructor then closes the
819 # calling object, but it's still in a method), and then the
820 # now-dead object does its second write. that is this case. we
821 # just lie and say it worked. it'll be dead soon and won't be
823 return 1 if $self->{closed};
827 # just queue data if there's already a wait
831 $bref = ref $data ? $data : \$data;
832 if ($self->{write_buf_size}) {
833 push @{$self->{write_buf}}, $bref;
834 $self->{write_buf_size} += ref $bref eq "SCALAR" ? length($$bref) : 1;
838 # this flag says we're bypassing the queue system, knowing we're the
839 # only outstanding write, and hoping we don't ever need to use it.
840 # if so later, though, we'll need to queue
846 return 1 unless $bref ||= $self->{write_buf}[0];
850 $len = length($$bref); # this will die if $bref is a code ref, caught below
853 if (UNIVERSAL::isa($bref, "CODE")) {
854 unless ($need_queue) {
855 $self->{write_buf_size}--; # code refs are worth 1
856 shift @{$self->{write_buf}};
860 # code refs are just run and never get reenqueued
861 # (they're one-shot), so turn off the flag indicating the
862 # outstanding data needs queueing.
868 die "Write error: $@ <$bref>";
871 my $to_write = $len - $self->{write_buf_offset};
873 if (my $wtr = $self->{writer_func}) {
874 $written = $wtr->($bref, $to_write, $self->{write_buf_offset});
876 $written = syswrite($self->{sock}, $$bref, $to_write, $self->{write_buf_offset});
879 if (! defined $written) {
881 return $self->close("EPIPE");
882 } elsif ($! == EAGAIN) {
883 # since connection has stuff to write, it should now be
884 # interested in pending writes:
886 push @{$self->{write_buf}}, $bref;
887 $self->{write_buf_size} += $len;
889 $self->{write_set_watch} = 1 unless $self->{event_watch} & POLLOUT;
890 $self->watch_write(1);
892 } elsif ($! == ECONNRESET) {
893 return $self->close("ECONNRESET");
896 DebugLevel >= 1 && $self->debugmsg("Closing connection ($self) due to write error: $!\n");
898 return $self->close("write_error");
899 } elsif ($written != $to_write) {
900 DebugLevel >= 2 && $self->debugmsg("Wrote PARTIAL %d bytes to %d",
901 $written, $self->{fd});
903 push @{$self->{write_buf}}, $bref;
904 $self->{write_buf_size} += $len;
906 # since connection has stuff to write, it should now be
907 # interested in pending writes:
908 $self->{write_buf_offset} += $written;
909 $self->{write_buf_size} -= $written;
910 $self->on_incomplete_write;
912 } elsif ($written == $to_write) {
913 DebugLevel >= 2 && $self->debugmsg("Wrote ALL %d bytes to %d (nq=%d)",
914 $written, $self->{fd}, $need_queue);
915 $self->{write_buf_offset} = 0;
917 if ($self->{write_set_watch}) {
918 $self->watch_write(0);
919 $self->{write_set_watch} = 0;
922 # this was our only write, so we can return immediately
923 # since we avoided incrementing the buffer size or
924 # putting it in the buffer. we also know there
925 # can't be anything else to write.
926 return 1 if $need_queue;
928 $self->{write_buf_size} -= $written;
929 shift @{$self->{write_buf}};
936 sub on_incomplete_write {
937 my PublicInbox::DS $self = shift;
938 $self->{write_set_watch} = 1 unless $self->{event_watch} & POLLOUT;
939 $self->watch_write(1);
942 =head2 C<< $obj->read( $bytecount ) >>
944 Read at most I<bytecount> bytes from the underlying handle; returns scalar
945 ref on read, or undef on connection closed.
949 my PublicInbox::DS $self = shift;
950 return if $self->{closed};
953 my $sock = $self->{sock};
955 # if this is too high, perl quits(!!). reports on mailing lists
956 # don't seem to point to a universal answer. 5MB worked for some,
957 # crashed for others. 1MB works for more people. let's go with 1MB
959 my $req_bytes = $bytes > 1048576 ? 1048576 : $bytes;
961 my $res = sysread($sock, $buf, $req_bytes, 0);
962 DebugLevel >= 2 && $self->debugmsg("sysread = %d; \$! = %d", $res, $!);
964 if (! $res && $! != EWOULDBLOCK) {
965 # catches 0=conn closed or undef=error
966 DebugLevel >= 2 && $self->debugmsg("Fd \#%d read hit the end of the road.", $self->{fd});
973 =head2 (VIRTUAL) C<< $obj->event_read() >>
975 Readable event handler. Concrete deriviatives of PublicInbox::DS should
976 provide an implementation of this. The default implementation will die if
980 sub event_read { die "Base class event_read called for $_[0]\n"; }
982 =head2 (VIRTUAL) C<< $obj->event_err() >>
984 Error event handler. Concrete deriviatives of PublicInbox::DS should
985 provide an implementation of this. The default implementation will die if
989 sub event_err { die "Base class event_err called for $_[0]\n"; }
991 =head2 (VIRTUAL) C<< $obj->event_hup() >>
993 'Hangup' event handler. Concrete deriviatives of PublicInbox::DS should
994 provide an implementation of this. The default implementation will die if
998 sub event_hup { die "Base class event_hup called for $_[0]\n"; }
1000 =head2 C<< $obj->event_write() >>
1002 Writable event handler. Concrete deriviatives of PublicInbox::DS may wish to
1003 provide an implementation of this. The default implementation calls
1004 C<write()> with an C<undef>.
1009 $self->write(undef);
1012 =head2 C<< $obj->watch_read( $boolean ) >>
1014 Turn 'readable' event notification on or off.
1018 my PublicInbox::DS $self = shift;
1019 return if $self->{closed} || !$self->{sock};
1022 my $event = $self->{event_watch};
1024 $event &= ~POLLIN if ! $val;
1025 $event |= POLLIN if $val;
1027 # If it changed, set it
1028 if ($event != $self->{event_watch}) {
1030 $KQueue->EV_SET($self->{fd}, IO::KQueue::EVFILT_READ(),
1031 $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
1033 elsif ($HaveEpoll) {
1034 epoll_ctl($Epoll, EPOLL_CTL_MOD, $self->{fd}, $event)
1035 and $self->dump_error("couldn't modify epoll settings for $self->{fd} " .
1036 "from $self->{event_watch} -> $event: $! (" . ($!+0) . ")");
1038 $self->{event_watch} = $event;
1042 =head2 C<< $obj->watch_write( $boolean ) >>
1044 Turn 'writable' event notification on or off.
1048 my PublicInbox::DS $self = shift;
1049 return if $self->{closed} || !$self->{sock};
1052 my $event = $self->{event_watch};
1054 $event &= ~POLLOUT if ! $val;
1055 $event |= POLLOUT if $val;
1057 if ($val && caller ne __PACKAGE__) {
1058 # A subclass registered interest, it's now responsible for this.
1059 $self->{write_set_watch} = 0;
1062 # If it changed, set it
1063 if ($event != $self->{event_watch}) {
1065 $KQueue->EV_SET($self->{fd}, IO::KQueue::EVFILT_WRITE(),
1066 $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
1068 elsif ($HaveEpoll) {
1069 epoll_ctl($Epoll, EPOLL_CTL_MOD, $self->{fd}, $event)
1070 and $self->dump_error("couldn't modify epoll settings for $self->{fd} " .
1071 "from $self->{event_watch} -> $event: $! (" . ($!+0) . ")");
1073 $self->{event_watch} = $event;
1077 =head2 C<< $obj->dump_error( $message ) >>
1079 Prints to STDERR a backtrace with information about this socket and what lead
1080 up to the dump_error call.
1086 while (my ($file, $line, $sub) = (caller($i++))[1..3]) {
1087 push @list, "\t$file:$line called $sub\n";
1090 warn "ERROR: $_[1]\n" .
1091 "\t$_[0] = " . $_[0]->as_string . "\n" .
1095 =head2 C<< $obj->debugmsg( $format, @args ) >>
1097 Print the debugging message specified by the C<sprintf>-style I<format> and
1102 my ( $self, $fmt, @args ) = @_;
1103 confess "Not an object" unless ref $self;
1106 printf STDERR ">>> $fmt\n", @args;
1109 =head2 C<< $obj->as_string() >>
1111 Returns a string describing this socket.
1115 my PublicInbox::DS $self = shift;
1116 my $rw = "(" . ($self->{event_watch} & POLLIN ? 'R' : '') .
1117 ($self->{event_watch} & POLLOUT ? 'W' : '') . ")";
1118 my $ret = ref($self) . "$rw: " . ($self->{closed} ? "closed" : "open");
1123 return undef unless $ENV{DS_DEBUG};
1124 my $msg = shift || "";
1125 warn "PublicInbox::DS: $msg\n";
1129 package PublicInbox::DS::Timer;
1130 # [$abs_float_firetime, $coderef];
1137 =head1 AUTHORS (Danga::Socket)
1139 Brad Fitzpatrick <brad@danga.com> - author
1141 Michael Granger <ged@danga.com> - docs, testing
1143 Mark Smith <junior@danga.com> - contributor, heavy user, testing
1145 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits