]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/DS.pm
ds: drop set_writer_func support
[public-inbox.git] / lib / PublicInbox / DS.pm
1 # This library is free software; you can redistribute it and/or modify
2 # it under the same terms as Perl itself.
3 #
4 # This license differs from the rest of public-inbox
5 #
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.
9 #
10 # API changes to diverge from Danga::Socket will happen to better
11 # accomodate new features and improve scalability.  Do not expect
12 # this to be a stable API like Danga::Socket.
13 # Bugs encountered (and likely fixed) are reported to
14 # bug-Danga-Socket@rt.cpan.org and visible at:
15 # https://rt.cpan.org/Public/Dist/Display.html?Name=Danga-Socket
16 package PublicInbox::DS;
17 use strict;
18 use bytes;
19 use POSIX ();
20 use Time::HiRes ();
21 use IO::Handle qw();
22 use Fcntl qw(FD_CLOEXEC F_SETFD F_GETFD);
23
24 use warnings;
25
26 use PublicInbox::Syscall qw(:epoll);
27
28 use fields ('sock',              # underlying socket
29             'fd',                # numeric file descriptor
30             'write_buf',         # arrayref of scalars, scalarrefs, or coderefs to write
31             'write_buf_offset',  # offset into first array of write_buf to start writing at
32             'write_buf_size',    # total length of data in all write_buf items
33             'write_set_watch',   # bool: true if we internally set watch_write rather than by a subclass
34             'closed',            # bool: socket is closed
35             'event_watch',       # bitmask of events the client is interested in (POLLIN,OUT,etc.)
36             );
37
38 use Errno  qw(EINPROGRESS EWOULDBLOCK EISCONN ENOTSOCK
39               EPIPE EAGAIN EBADF ECONNRESET ENOPROTOOPT);
40 use Carp   qw(croak confess);
41
42 use constant DebugLevel => 0;
43
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;
49
50 our $HAVE_KQUEUE = eval { require IO::KQueue; 1 };
51
52 our (
53      $HaveEpoll,                 # Flag -- is epoll available?  initially undefined.
54      $HaveKQueue,
55      %DescriptorMap,             # fd (num) -> PublicInbox::DS object
56      $Epoll,                     # Global epoll fd (for epoll mode only)
57      $KQueue,                    # Global kqueue fd ref (for kqueue mode only)
58      $_io,                       # IO::Handle for Epoll
59      @ToClose,                   # sockets to close when event loop is done
60
61      $PostLoopCallback,          # subref to call at the end of each loop, if defined (global)
62      %PLCMap,                    # fd (num) -> PostLoopCallback (per-object)
63
64      $LoopTimeout,               # timeout of event loop in milliseconds
65      $DoneInit,                  # if we've done the one-time module init yet
66      @Timers,                    # timers
67      );
68
69 # this may be set to zero with old kernels
70 our $EPOLLEXCLUSIVE = EPOLLEXCLUSIVE;
71 Reset();
72
73 #####################################################################
74 ### C L A S S   M E T H O D S
75 #####################################################################
76
77 =head2 C<< CLASS->Reset() >>
78
79 Reset all state
80
81 =cut
82 sub Reset {
83     %DescriptorMap = ();
84     @ToClose = ();
85     $LoopTimeout = -1;  # no timeout by default
86     @Timers = ();
87
88     $PostLoopCallback = undef;
89     %PLCMap = ();
90     $DoneInit = 0;
91
92     # NOTE kqueue is close-on-fork, and we don't account for it, yet
93     # OTOH, we (public-inbox) don't need this sub outside of tests...
94     POSIX::close($$KQueue) if !$_io && $KQueue && $$KQueue >= 0;
95     $KQueue = undef;
96
97     $_io = undef; # close $Epoll
98     $Epoll = undef;
99
100     *EventLoop = *FirstTimeEventLoop;
101 }
102
103 =head2 C<< CLASS->SetLoopTimeout( $timeout ) >>
104
105 Set the loop timeout for the event loop to some value in milliseconds.
106
107 A timeout of 0 (zero) means poll forever. A timeout of -1 means poll and return
108 immediately.
109
110 =cut
111 sub SetLoopTimeout {
112     return $LoopTimeout = $_[1] + 0;
113 }
114
115 =head2 C<< CLASS->DebugMsg( $format, @args ) >>
116
117 Print the debugging message specified by the C<sprintf>-style I<format> and
118 I<args>
119
120 =cut
121 sub DebugMsg {
122     my ( $class, $fmt, @args ) = @_;
123     chomp $fmt;
124     printf STDERR ">>> $fmt\n", @args;
125 }
126
127 =head2 C<< CLASS->AddTimer( $seconds, $coderef ) >>
128
129 Add a timer to occur $seconds from now. $seconds may be fractional, but timers
130 are not guaranteed to fire at the exact time you ask for.
131
132 Returns a timer object which you can call C<< $timer->cancel >> on if you need to.
133
134 =cut
135 sub AddTimer {
136     my $class = shift;
137     my ($secs, $coderef) = @_;
138
139     my $fire_time = Time::HiRes::time() + $secs;
140
141     my $timer = bless [$fire_time, $coderef], "PublicInbox::DS::Timer";
142
143     if (!@Timers || $fire_time >= $Timers[-1][0]) {
144         push @Timers, $timer;
145         return $timer;
146     }
147
148     # Now, where do we insert?  (NOTE: this appears slow, algorithm-wise,
149     # but it was compared against calendar queues, heaps, naive push/sort,
150     # and a bunch of other versions, and found to be fastest with a large
151     # variety of datasets.)
152     for (my $i = 0; $i < @Timers; $i++) {
153         if ($Timers[$i][0] > $fire_time) {
154             splice(@Timers, $i, 0, $timer);
155             return $timer;
156         }
157     }
158
159     die "Shouldn't get here.";
160 }
161
162 # keeping this around in case we support other FD types for now,
163 # epoll_create1(EPOLL_CLOEXEC) requires Linux 2.6.27+...
164 sub set_cloexec ($) {
165     my ($fd) = @_;
166
167     $_io = IO::Handle->new_from_fd($fd, 'r+') or return;
168     defined(my $fl = fcntl($_io, F_GETFD, 0)) or return;
169     fcntl($_io, F_SETFD, $fl | FD_CLOEXEC);
170 }
171
172 sub _InitPoller
173 {
174     return if $DoneInit;
175     $DoneInit = 1;
176
177     if ($HAVE_KQUEUE) {
178         $KQueue = IO::KQueue->new();
179         $HaveKQueue = defined $KQueue;
180         if ($HaveKQueue) {
181             *EventLoop = *KQueueEventLoop;
182         }
183     }
184     elsif (PublicInbox::Syscall::epoll_defined()) {
185         $Epoll = eval { epoll_create(1024); };
186         $HaveEpoll = defined $Epoll && $Epoll >= 0;
187         if ($HaveEpoll) {
188             set_cloexec($Epoll);
189             *EventLoop = *EpollEventLoop;
190         }
191     }
192
193     if (!$HaveEpoll && !$HaveKQueue) {
194         require IO::Poll;
195         *EventLoop = *PollEventLoop;
196     }
197 }
198
199 =head2 C<< CLASS->EventLoop() >>
200
201 Start processing IO events. In most daemon programs this never exits. See
202 C<PostLoopCallback> below for how to exit the loop.
203
204 =cut
205 sub FirstTimeEventLoop {
206     my $class = shift;
207
208     _InitPoller();
209
210     if ($HaveEpoll) {
211         EpollEventLoop($class);
212     } elsif ($HaveKQueue) {
213         KQueueEventLoop($class);
214     } else {
215         PollEventLoop($class);
216     }
217 }
218
219 # runs timers and returns milliseconds for next one, or next event loop
220 sub RunTimers {
221     return $LoopTimeout unless @Timers;
222
223     my $now = Time::HiRes::time();
224
225     # Run expired timers
226     while (@Timers && $Timers[0][0] <= $now) {
227         my $to_run = shift(@Timers);
228         $to_run->[1]->($now) if $to_run->[1];
229     }
230
231     return $LoopTimeout unless @Timers;
232
233     # convert time to an even number of milliseconds, adding 1
234     # extra, otherwise floating point fun can occur and we'll
235     # call RunTimers like 20-30 times, each returning a timeout
236     # of 0.0000212 seconds
237     my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
238
239     # -1 is an infinite timeout, so prefer a real timeout
240     return $timeout     if $LoopTimeout == -1;
241
242     # otherwise pick the lower of our regular timeout and time until
243     # the next timer
244     return $LoopTimeout if $LoopTimeout < $timeout;
245     return $timeout;
246 }
247
248 ### The epoll-based event loop. Gets installed as EventLoop if IO::Epoll loads
249 ### okay.
250 sub EpollEventLoop {
251     my $class = shift;
252
253     while (1) {
254         my @events;
255         my $i;
256         my $timeout = RunTimers();
257
258         # get up to 1000 events
259         my $evcount = epoll_wait($Epoll, 1000, $timeout, \@events);
260       EVENT:
261         for ($i=0; $i<$evcount; $i++) {
262             my $ev = $events[$i];
263
264             # it's possible epoll_wait returned many events, including some at the end
265             # that ones in the front triggered unregister-interest actions.  if we
266             # can't find the %sock entry, it's because we're no longer interested
267             # in that event.
268             my PublicInbox::DS $pob = $DescriptorMap{$ev->[0]};
269             my $code;
270             my $state = $ev->[1];
271
272             # if we didn't find a Perlbal::Socket subclass for that fd, try other
273             # pseudo-registered (above) fds.
274             if (! $pob) {
275                 my $fd = $ev->[0];
276                 warn "epoll() returned fd $fd w/ state $state for which we have no mapping.  removing.\n";
277                 epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, 0);
278                 POSIX::close($fd);
279                 next;
280             }
281
282             DebugLevel >= 1 && $class->DebugMsg("Event: fd=%d (%s), state=%d \@ %s\n",
283                                                 $ev->[0], ref($pob), $ev->[1], time);
284
285             # standard non-profiling codepat
286             $pob->event_read   if $state & EPOLLIN && ! $pob->{closed};
287             $pob->event_write  if $state & EPOLLOUT && ! $pob->{closed};
288             if ($state & (EPOLLERR|EPOLLHUP)) {
289                 $pob->event_err    if $state & EPOLLERR && ! $pob->{closed};
290                 $pob->event_hup    if $state & EPOLLHUP && ! $pob->{closed};
291             }
292         }
293         return unless PostEventLoop();
294     }
295     exit 0;
296 }
297
298 ### The fallback IO::Poll-based event loop. Gets installed as EventLoop if
299 ### IO::Epoll fails to load.
300 sub PollEventLoop {
301     my $class = shift;
302
303     my PublicInbox::DS $pob;
304
305     while (1) {
306         my $timeout = RunTimers();
307
308         # the following sets up @poll as a series of ($poll,$event_mask)
309         # items, then uses IO::Poll::_poll, implemented in XS, which
310         # modifies the array in place with the even elements being
311         # replaced with the event masks that occured.
312         my @poll;
313         while ( my ($fd, $sock) = each %DescriptorMap ) {
314             push @poll, $fd, $sock->{event_watch};
315         }
316
317         # if nothing to poll, either end immediately (if no timeout)
318         # or just keep calling the callback
319         unless (@poll) {
320             select undef, undef, undef, ($timeout / 1000);
321             return unless PostEventLoop();
322             next;
323         }
324
325         my $count = IO::Poll::_poll($timeout, @poll);
326         unless ($count >= 0) {
327             return unless PostEventLoop();
328             next;
329         }
330
331         # Fetch handles with read events
332         while (@poll) {
333             my ($fd, $state) = splice(@poll, 0, 2);
334             next unless $state;
335
336             $pob = $DescriptorMap{$fd};
337
338             if (!$pob) {
339                 next;
340             }
341
342             $pob->event_read   if $state & POLLIN && ! $pob->{closed};
343             $pob->event_write  if $state & POLLOUT && ! $pob->{closed};
344             $pob->event_err    if $state & POLLERR && ! $pob->{closed};
345             $pob->event_hup    if $state & POLLHUP && ! $pob->{closed};
346         }
347
348         return unless PostEventLoop();
349     }
350
351     exit 0;
352 }
353
354 ### The kqueue-based event loop. Gets installed as EventLoop if IO::KQueue works
355 ### okay.
356 sub KQueueEventLoop {
357     my $class = shift;
358
359     while (1) {
360         my $timeout = RunTimers();
361         my @ret = eval { $KQueue->kevent($timeout) };
362         if (my $err = $@) {
363             # workaround https://rt.cpan.org/Ticket/Display.html?id=116615
364             if ($err =~ /Interrupted system call/) {
365                 @ret = ();
366             } else {
367                 die $err;
368             }
369         }
370
371         foreach my $kev (@ret) {
372             my ($fd, $filter, $flags, $fflags) = @$kev;
373             my PublicInbox::DS $pob = $DescriptorMap{$fd};
374             if (!$pob) {
375                 warn "kevent() returned fd $fd for which we have no mapping.  removing.\n";
376                 POSIX::close($fd); # close deletes the kevent entry
377                 next;
378             }
379
380             DebugLevel >= 1 && $class->DebugMsg("Event: fd=%d (%s), flags=%d \@ %s\n",
381                                                         $fd, ref($pob), $flags, time);
382
383             $pob->event_read  if $filter == IO::KQueue::EVFILT_READ()  && !$pob->{closed};
384             $pob->event_write if $filter == IO::KQueue::EVFILT_WRITE() && !$pob->{closed};
385             if ($flags ==  IO::KQueue::EV_EOF() && !$pob->{closed}) {
386                 if ($fflags) {
387                     $pob->event_err;
388                 } else {
389                     $pob->event_hup;
390                 }
391             }
392         }
393         return unless PostEventLoop();
394     }
395
396     exit(0);
397 }
398
399 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
400
401 Sets post loop callback function.  Pass a subref and it will be
402 called every time the event loop finishes.
403
404 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
405 and it will exit.
406
407 The callback function will be passed two parameters: \%DescriptorMap
408
409 =cut
410 sub SetPostLoopCallback {
411     my ($class, $ref) = @_;
412
413     if (ref $class) {
414         # per-object callback
415         my PublicInbox::DS $self = $class;
416         if (defined $ref && ref $ref eq 'CODE') {
417             $PLCMap{$self->{fd}} = $ref;
418         } else {
419             delete $PLCMap{$self->{fd}};
420         }
421     } else {
422         # global callback
423         $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
424     }
425 }
426
427 # Internal function: run the post-event callback, send read events
428 # for pushed-back data, and close pending connections.  returns 1
429 # if event loop should continue, or 0 to shut it all down.
430 sub PostEventLoop {
431     # now we can close sockets that wanted to close during our event processing.
432     # (we didn't want to close them during the loop, as we didn't want fd numbers
433     #  being reused and confused during the event loop)
434     while (my $sock = shift @ToClose) {
435         my $fd = fileno($sock);
436
437         # close the socket.  (not a PublicInbox::DS close)
438         $sock->close;
439
440         # and now we can finally remove the fd from the map.  see
441         # comment above in _cleanup.
442         delete $DescriptorMap{$fd};
443     }
444
445
446     # by default we keep running, unless a postloop callback (either per-object
447     # or global) cancels it
448     my $keep_running = 1;
449
450     # per-object post-loop-callbacks
451     for my $plc (values %PLCMap) {
452         $keep_running &&= $plc->(\%DescriptorMap);
453     }
454
455     # now we're at the very end, call callback if defined
456     if (defined $PostLoopCallback) {
457         $keep_running &&= $PostLoopCallback->(\%DescriptorMap);
458     }
459
460     return $keep_running;
461 }
462
463 #####################################################################
464 ### PublicInbox::DS-the-object code
465 #####################################################################
466
467 =head2 OBJECT METHODS
468
469 =head2 C<< CLASS->new( $socket ) >>
470
471 Create a new PublicInbox::DS subclass object for the given I<socket> which will
472 react to events on it during the C<EventLoop>.
473
474 This is normally (always?) called from your subclass via:
475
476   $class->SUPER::new($socket);
477
478 =cut
479 sub new {
480     my ($self, $sock, $exclusive) = @_;
481     $self = fields::new($self) unless ref $self;
482
483     $self->{sock}        = $sock;
484     my $fd = fileno($sock);
485
486     Carp::cluck("undef sock and/or fd in PublicInbox::DS->new.  sock=" . ($sock || "") . ", fd=" . ($fd || ""))
487         unless $sock && $fd;
488
489     $self->{fd}          = $fd;
490     $self->{write_buf}      = [];
491     $self->{write_buf_offset} = 0;
492     $self->{write_buf_size} = 0;
493     $self->{closed} = 0;
494
495     my $ev = $self->{event_watch} = POLLERR|POLLHUP|POLLNVAL;
496
497     _InitPoller();
498
499     if ($HaveEpoll) {
500         if ($exclusive) {
501             $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP|$EPOLLEXCLUSIVE;
502         }
503 retry:
504         if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
505             if ($!{EINVAL} && ($ev & $EPOLLEXCLUSIVE)) {
506                 $EPOLLEXCLUSIVE = 0; # old kernel
507                 $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP;
508                 goto retry;
509             }
510             die "couldn't add epoll watch for $fd: $!\n";
511         }
512     }
513     elsif ($HaveKQueue) {
514         # Add them to the queue but disabled for now
515         $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(),
516                         IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
517         $KQueue->EV_SET($fd, IO::KQueue::EVFILT_WRITE(),
518                         IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
519     }
520
521     Carp::cluck("PublicInbox::DS::new blowing away existing descriptor map for fd=$fd ($DescriptorMap{$fd})")
522         if $DescriptorMap{$fd};
523
524     $DescriptorMap{$fd} = $self;
525     return $self;
526 }
527
528
529 #####################################################################
530 ### I N S T A N C E   M E T H O D S
531 #####################################################################
532
533 =head2 C<< $obj->steal_socket() >>
534
535 Basically returns our socket and makes it so that we don't try to close it,
536 but we do remove it from epoll handlers.  THIS CLOSES $self.  It is the same
537 thing as calling close, except it gives you the socket to use.
538
539 =cut
540 sub steal_socket {
541     my PublicInbox::DS $self = $_[0];
542     return if $self->{closed};
543
544     # cleanup does most of the work of closing this socket
545     $self->_cleanup();
546
547     # now undef our internal sock and fd structures so we don't use them
548     my $sock = $self->{sock};
549     $self->{sock} = undef;
550     return $sock;
551 }
552
553 =head2 C<< $obj->close( [$reason] ) >>
554
555 Close the socket. The I<reason> argument will be used in debugging messages.
556
557 =cut
558 sub close {
559     my PublicInbox::DS $self = $_[0];
560     return if $self->{closed};
561
562     # print out debugging info for this close
563     if (DebugLevel) {
564         my ($pkg, $filename, $line) = caller;
565         my $reason = $_[1] || "";
566         warn "Closing \#$self->{fd} due to $pkg/$filename/$line ($reason)\n";
567     }
568
569     # this does most of the work of closing us
570     $self->_cleanup();
571
572     # defer closing the actual socket until the event loop is done
573     # processing this round of events.  (otherwise we might reuse fds)
574     if ($self->{sock}) {
575         push @ToClose, $self->{sock};
576         $self->{sock} = undef;
577     }
578
579     return 0;
580 }
581
582 ### METHOD: _cleanup()
583 ### Called by our closers so we can clean internal data structures.
584 sub _cleanup {
585     my PublicInbox::DS $self = $_[0];
586
587     # we're effectively closed; we have no fd and sock when we leave here
588     $self->{closed} = 1;
589
590     # we need to flush our write buffer, as there may
591     # be self-referential closures (sub { $client->close })
592     # preventing the object from being destroyed
593     $self->{write_buf} = [];
594
595     # if we're using epoll, we have to remove this from our epoll fd so we stop getting
596     # notifications about it
597     if ($HaveEpoll && $self->{fd}) {
598         if (epoll_ctl($Epoll, EPOLL_CTL_DEL, $self->{fd}, $self->{event_watch}) != 0) {
599             # dump_error prints a backtrace so we can try to figure out why this happened
600             $self->dump_error("epoll_ctl(): failure deleting fd=$self->{fd} during _cleanup(); $! (" . ($!+0) . ")");
601         }
602     }
603
604     # now delete from mappings.  this fd no longer belongs to us, so we don't want
605     # to get alerts for it if it becomes writable/readable/etc.
606     delete $PLCMap{$self->{fd}};
607
608     # we explicitly don't delete from DescriptorMap here until we
609     # actually close the socket, as we might be in the middle of
610     # processing an epoll_wait/etc that returned hundreds of fds, one
611     # of which is not yet processed and is what we're closing.  if we
612     # keep it in DescriptorMap, then the event harnesses can just
613     # looked at $pob->{closed} and ignore it.  but if it's an
614     # un-accounted for fd, then it (understandably) freak out a bit
615     # and emit warnings, thinking their state got off.
616
617     # and finally get rid of our fd so we can't use it anywhere else
618     $self->{fd} = undef;
619 }
620
621 =head2 C<< $obj->sock() >>
622
623 Returns the underlying IO::Handle for the object.
624
625 =cut
626 sub sock {
627     my PublicInbox::DS $self = shift;
628     return $self->{sock};
629 }
630
631 =head2 C<< $obj->write( $data ) >>
632
633 Write the specified data to the underlying handle.  I<data> may be scalar,
634 scalar ref, code ref (to run when there), or undef just to kick-start.
635 Returns 1 if writes all went through, or 0 if there are writes in queue. If
636 it returns 1, caller should stop waiting for 'writable' events)
637
638 =cut
639 sub write {
640     my PublicInbox::DS $self;
641     my $data;
642     ($self, $data) = @_;
643
644     # nobody should be writing to closed sockets, but caller code can
645     # do two writes within an event, have the first fail and
646     # disconnect the other side (whose destructor then closes the
647     # calling object, but it's still in a method), and then the
648     # now-dead object does its second write.  that is this case.  we
649     # just lie and say it worked.  it'll be dead soon and won't be
650     # hurt by this lie.
651     return 1 if $self->{closed};
652
653     my $bref;
654
655     # just queue data if there's already a wait
656     my $need_queue;
657
658     if (defined $data) {
659         $bref = ref $data ? $data : \$data;
660         if ($self->{write_buf_size}) {
661             push @{$self->{write_buf}}, $bref;
662             $self->{write_buf_size} += ref $bref eq "SCALAR" ? length($$bref) : 1;
663             return 0;
664         }
665
666         # this flag says we're bypassing the queue system, knowing we're the
667         # only outstanding write, and hoping we don't ever need to use it.
668         # if so later, though, we'll need to queue
669         $need_queue = 1;
670     }
671
672   WRITE:
673     while (1) {
674         return 1 unless $bref ||= $self->{write_buf}[0];
675
676         my $len;
677         eval {
678             $len = length($$bref); # this will die if $bref is a code ref, caught below
679         };
680         if ($@) {
681             if (UNIVERSAL::isa($bref, "CODE")) {
682                 unless ($need_queue) {
683                     $self->{write_buf_size}--; # code refs are worth 1
684                     shift @{$self->{write_buf}};
685                 }
686                 $bref->();
687
688                 # code refs are just run and never get reenqueued
689                 # (they're one-shot), so turn off the flag indicating the
690                 # outstanding data needs queueing.
691                 $need_queue = 0;
692
693                 undef $bref;
694                 next WRITE;
695             }
696             die "Write error: $@ <$bref>";
697         }
698
699         my $to_write = $len - $self->{write_buf_offset};
700         my $written = syswrite($self->{sock}, $$bref, $to_write,
701                                $self->{write_buf_offset});
702
703         if (! defined $written) {
704             if ($! == EPIPE) {
705                 return $self->close("EPIPE");
706             } elsif ($! == EAGAIN) {
707                 # since connection has stuff to write, it should now be
708                 # interested in pending writes:
709                 if ($need_queue) {
710                     push @{$self->{write_buf}}, $bref;
711                     $self->{write_buf_size} += $len;
712                 }
713                 $self->{write_set_watch} = 1 unless $self->{event_watch} & POLLOUT;
714                 $self->watch_write(1);
715                 return 0;
716             } elsif ($! == ECONNRESET) {
717                 return $self->close("ECONNRESET");
718             }
719
720             DebugLevel >= 1 && $self->debugmsg("Closing connection ($self) due to write error: $!\n");
721
722             return $self->close("write_error");
723         } elsif ($written != $to_write) {
724             DebugLevel >= 2 && $self->debugmsg("Wrote PARTIAL %d bytes to %d",
725                                                $written, $self->{fd});
726             if ($need_queue) {
727                 push @{$self->{write_buf}}, $bref;
728                 $self->{write_buf_size} += $len;
729             }
730             # since connection has stuff to write, it should now be
731             # interested in pending writes:
732             $self->{write_buf_offset} += $written;
733             $self->{write_buf_size} -= $written;
734             $self->on_incomplete_write;
735             return 0;
736         } elsif ($written == $to_write) {
737             DebugLevel >= 2 && $self->debugmsg("Wrote ALL %d bytes to %d (nq=%d)",
738                                                $written, $self->{fd}, $need_queue);
739             $self->{write_buf_offset} = 0;
740
741             if ($self->{write_set_watch}) {
742                 $self->watch_write(0);
743                 $self->{write_set_watch} = 0;
744             }
745
746             # this was our only write, so we can return immediately
747             # since we avoided incrementing the buffer size or
748             # putting it in the buffer.  we also know there
749             # can't be anything else to write.
750             return 1 if $need_queue;
751
752             $self->{write_buf_size} -= $written;
753             shift @{$self->{write_buf}};
754             undef $bref;
755             next WRITE;
756         }
757     }
758 }
759
760 sub on_incomplete_write {
761     my PublicInbox::DS $self = shift;
762     $self->{write_set_watch} = 1 unless $self->{event_watch} & POLLOUT;
763     $self->watch_write(1);
764 }
765
766 =head2 C<< $obj->read( $bytecount ) >>
767
768 Read at most I<bytecount> bytes from the underlying handle; returns scalar
769 ref on read, or undef on connection closed.
770
771 =cut
772 sub read {
773     my PublicInbox::DS $self = shift;
774     return if $self->{closed};
775     my $bytes = shift;
776     my $buf;
777     my $sock = $self->{sock};
778
779     # if this is too high, perl quits(!!).  reports on mailing lists
780     # don't seem to point to a universal answer.  5MB worked for some,
781     # crashed for others.  1MB works for more people.  let's go with 1MB
782     # for now.  :/
783     my $req_bytes = $bytes > 1048576 ? 1048576 : $bytes;
784
785     my $res = sysread($sock, $buf, $req_bytes, 0);
786     DebugLevel >= 2 && $self->debugmsg("sysread = %d; \$! = %d", $res, $!);
787
788     if (! $res && $! != EWOULDBLOCK) {
789         # catches 0=conn closed or undef=error
790         DebugLevel >= 2 && $self->debugmsg("Fd \#%d read hit the end of the road.", $self->{fd});
791         return undef;
792     }
793
794     return \$buf;
795 }
796
797 =head2 (VIRTUAL) C<< $obj->event_read() >>
798
799 Readable event handler. Concrete deriviatives of PublicInbox::DS should
800 provide an implementation of this. The default implementation will die if
801 called.
802
803 =cut
804 sub event_read  { die "Base class event_read called for $_[0]\n"; }
805
806 =head2 (VIRTUAL) C<< $obj->event_err() >>
807
808 Error event handler. Concrete deriviatives of PublicInbox::DS should
809 provide an implementation of this. The default implementation will die if
810 called.
811
812 =cut
813 sub event_err   { die "Base class event_err called for $_[0]\n"; }
814
815 =head2 (VIRTUAL) C<< $obj->event_hup() >>
816
817 'Hangup' event handler. Concrete deriviatives of PublicInbox::DS should
818 provide an implementation of this. The default implementation will die if
819 called.
820
821 =cut
822 sub event_hup   { die "Base class event_hup called for $_[0]\n"; }
823
824 =head2 C<< $obj->event_write() >>
825
826 Writable event handler. Concrete deriviatives of PublicInbox::DS may wish to
827 provide an implementation of this. The default implementation calls
828 C<write()> with an C<undef>.
829
830 =cut
831 sub event_write {
832     my $self = shift;
833     $self->write(undef);
834 }
835
836 =head2 C<< $obj->watch_read( $boolean ) >>
837
838 Turn 'readable' event notification on or off.
839
840 =cut
841 sub watch_read {
842     my PublicInbox::DS $self = shift;
843     return if $self->{closed} || !$self->{sock};
844
845     my $val = shift;
846     my $event = $self->{event_watch};
847
848     $event &= ~POLLIN if ! $val;
849     $event |=  POLLIN if   $val;
850
851     # If it changed, set it
852     if ($event != $self->{event_watch}) {
853         if ($HaveKQueue) {
854             $KQueue->EV_SET($self->{fd}, IO::KQueue::EVFILT_READ(),
855                             $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
856         }
857         elsif ($HaveEpoll) {
858             epoll_ctl($Epoll, EPOLL_CTL_MOD, $self->{fd}, $event)
859                 and $self->dump_error("couldn't modify epoll settings for $self->{fd} " .
860                                       "from $self->{event_watch} -> $event: $! (" . ($!+0) . ")");
861         }
862         $self->{event_watch} = $event;
863     }
864 }
865
866 =head2 C<< $obj->watch_write( $boolean ) >>
867
868 Turn 'writable' event notification on or off.
869
870 =cut
871 sub watch_write {
872     my PublicInbox::DS $self = shift;
873     return if $self->{closed} || !$self->{sock};
874
875     my $val = shift;
876     my $event = $self->{event_watch};
877
878     $event &= ~POLLOUT if ! $val;
879     $event |=  POLLOUT if   $val;
880
881     if ($val && caller ne __PACKAGE__) {
882         # A subclass registered interest, it's now responsible for this.
883         $self->{write_set_watch} = 0;
884     }
885
886     # If it changed, set it
887     if ($event != $self->{event_watch}) {
888         if ($HaveKQueue) {
889             $KQueue->EV_SET($self->{fd}, IO::KQueue::EVFILT_WRITE(),
890                             $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
891         }
892         elsif ($HaveEpoll) {
893             epoll_ctl($Epoll, EPOLL_CTL_MOD, $self->{fd}, $event)
894                 and $self->dump_error("couldn't modify epoll settings for $self->{fd} " .
895                                       "from $self->{event_watch} -> $event: $! (" . ($!+0) . ")");
896         }
897         $self->{event_watch} = $event;
898     }
899 }
900
901 =head2 C<< $obj->dump_error( $message ) >>
902
903 Prints to STDERR a backtrace with information about this socket and what lead
904 up to the dump_error call.
905
906 =cut
907 sub dump_error {
908     my $i = 0;
909     my @list;
910     while (my ($file, $line, $sub) = (caller($i++))[1..3]) {
911         push @list, "\t$file:$line called $sub\n";
912     }
913
914     warn "ERROR: $_[1]\n" .
915         "\t$_[0] = " . $_[0]->as_string . "\n" .
916         join('', @list);
917 }
918
919 =head2 C<< $obj->debugmsg( $format, @args ) >>
920
921 Print the debugging message specified by the C<sprintf>-style I<format> and
922 I<args>.
923
924 =cut
925 sub debugmsg {
926     my ( $self, $fmt, @args ) = @_;
927     confess "Not an object" unless ref $self;
928
929     chomp $fmt;
930     printf STDERR ">>> $fmt\n", @args;
931 }
932
933 =head2 C<< $obj->as_string() >>
934
935 Returns a string describing this socket.
936
937 =cut
938 sub as_string {
939     my PublicInbox::DS $self = shift;
940     my $rw = "(" . ($self->{event_watch} & POLLIN ? 'R' : '') .
941                    ($self->{event_watch} & POLLOUT ? 'W' : '') . ")";
942     my $ret = ref($self) . "$rw: " . ($self->{closed} ? "closed" : "open");
943     return $ret;
944 }
945
946 package PublicInbox::DS::Timer;
947 # [$abs_float_firetime, $coderef];
948 sub cancel {
949     $_[0][1] = undef;
950 }
951
952 1;
953
954 =head1 AUTHORS (Danga::Socket)
955
956 Brad Fitzpatrick <brad@danga.com> - author
957
958 Michael Granger <ged@danga.com> - docs, testing
959
960 Mark Smith <junior@danga.com> - contributor, heavy user, testing
961
962 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits