]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/DS.pm
ds: drop unused EVENT: label in epoll code path
[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         for ($i=0; $i<$evcount; $i++) {
261             my $ev = $events[$i];
262
263             # it's possible epoll_wait returned many events, including some at the end
264             # that ones in the front triggered unregister-interest actions.  if we
265             # can't find the %sock entry, it's because we're no longer interested
266             # in that event.
267             my PublicInbox::DS $pob = $DescriptorMap{$ev->[0]};
268             my $code;
269             my $state = $ev->[1];
270
271             DebugLevel >= 1 && $class->DebugMsg("Event: fd=%d (%s), state=%d \@ %s\n",
272                                                 $ev->[0], ref($pob), $ev->[1], time);
273
274             # standard non-profiling codepat
275             $pob->event_read   if $state & EPOLLIN && ! $pob->{closed};
276             $pob->event_write  if $state & EPOLLOUT && ! $pob->{closed};
277             if ($state & (EPOLLERR|EPOLLHUP)) {
278                 $pob->event_err    if $state & EPOLLERR && ! $pob->{closed};
279                 $pob->event_hup    if $state & EPOLLHUP && ! $pob->{closed};
280             }
281         }
282         return unless PostEventLoop();
283     }
284     exit 0;
285 }
286
287 ### The fallback IO::Poll-based event loop. Gets installed as EventLoop if
288 ### IO::Epoll fails to load.
289 sub PollEventLoop {
290     my $class = shift;
291
292     my PublicInbox::DS $pob;
293
294     while (1) {
295         my $timeout = RunTimers();
296
297         # the following sets up @poll as a series of ($poll,$event_mask)
298         # items, then uses IO::Poll::_poll, implemented in XS, which
299         # modifies the array in place with the even elements being
300         # replaced with the event masks that occured.
301         my @poll;
302         while ( my ($fd, $sock) = each %DescriptorMap ) {
303             push @poll, $fd, $sock->{event_watch};
304         }
305
306         # if nothing to poll, either end immediately (if no timeout)
307         # or just keep calling the callback
308         unless (@poll) {
309             select undef, undef, undef, ($timeout / 1000);
310             return unless PostEventLoop();
311             next;
312         }
313
314         my $count = IO::Poll::_poll($timeout, @poll);
315         unless ($count >= 0) {
316             return unless PostEventLoop();
317             next;
318         }
319
320         # Fetch handles with read events
321         while (@poll) {
322             my ($fd, $state) = splice(@poll, 0, 2);
323             next unless $state;
324
325             $pob = $DescriptorMap{$fd};
326
327             $pob->event_read   if $state & POLLIN && ! $pob->{closed};
328             $pob->event_write  if $state & POLLOUT && ! $pob->{closed};
329             $pob->event_err    if $state & POLLERR && ! $pob->{closed};
330             $pob->event_hup    if $state & POLLHUP && ! $pob->{closed};
331         }
332
333         return unless PostEventLoop();
334     }
335
336     exit 0;
337 }
338
339 ### The kqueue-based event loop. Gets installed as EventLoop if IO::KQueue works
340 ### okay.
341 sub KQueueEventLoop {
342     my $class = shift;
343
344     while (1) {
345         my $timeout = RunTimers();
346         my @ret = eval { $KQueue->kevent($timeout) };
347         if (my $err = $@) {
348             # workaround https://rt.cpan.org/Ticket/Display.html?id=116615
349             if ($err =~ /Interrupted system call/) {
350                 @ret = ();
351             } else {
352                 die $err;
353             }
354         }
355
356         foreach my $kev (@ret) {
357             my ($fd, $filter, $flags, $fflags) = @$kev;
358             my PublicInbox::DS $pob = $DescriptorMap{$fd};
359
360             DebugLevel >= 1 && $class->DebugMsg("Event: fd=%d (%s), flags=%d \@ %s\n",
361                                                         $fd, ref($pob), $flags, time);
362
363             $pob->event_read  if $filter == IO::KQueue::EVFILT_READ()  && !$pob->{closed};
364             $pob->event_write if $filter == IO::KQueue::EVFILT_WRITE() && !$pob->{closed};
365             if ($flags ==  IO::KQueue::EV_EOF() && !$pob->{closed}) {
366                 if ($fflags) {
367                     $pob->event_err;
368                 } else {
369                     $pob->event_hup;
370                 }
371             }
372         }
373         return unless PostEventLoop();
374     }
375
376     exit(0);
377 }
378
379 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
380
381 Sets post loop callback function.  Pass a subref and it will be
382 called every time the event loop finishes.
383
384 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
385 and it will exit.
386
387 The callback function will be passed two parameters: \%DescriptorMap
388
389 =cut
390 sub SetPostLoopCallback {
391     my ($class, $ref) = @_;
392
393     if (ref $class) {
394         # per-object callback
395         my PublicInbox::DS $self = $class;
396         if (defined $ref && ref $ref eq 'CODE') {
397             $PLCMap{$self->{fd}} = $ref;
398         } else {
399             delete $PLCMap{$self->{fd}};
400         }
401     } else {
402         # global callback
403         $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
404     }
405 }
406
407 # Internal function: run the post-event callback, send read events
408 # for pushed-back data, and close pending connections.  returns 1
409 # if event loop should continue, or 0 to shut it all down.
410 sub PostEventLoop {
411     # now we can close sockets that wanted to close during our event processing.
412     # (we didn't want to close them during the loop, as we didn't want fd numbers
413     #  being reused and confused during the event loop)
414     while (my $sock = shift @ToClose) {
415         my $fd = fileno($sock);
416
417         # close the socket.  (not a PublicInbox::DS close)
418         $sock->close;
419
420         # and now we can finally remove the fd from the map.  see
421         # comment above in _cleanup.
422         delete $DescriptorMap{$fd};
423     }
424
425
426     # by default we keep running, unless a postloop callback (either per-object
427     # or global) cancels it
428     my $keep_running = 1;
429
430     # per-object post-loop-callbacks
431     for my $plc (values %PLCMap) {
432         $keep_running &&= $plc->(\%DescriptorMap);
433     }
434
435     # now we're at the very end, call callback if defined
436     if (defined $PostLoopCallback) {
437         $keep_running &&= $PostLoopCallback->(\%DescriptorMap);
438     }
439
440     return $keep_running;
441 }
442
443 #####################################################################
444 ### PublicInbox::DS-the-object code
445 #####################################################################
446
447 =head2 OBJECT METHODS
448
449 =head2 C<< CLASS->new( $socket ) >>
450
451 Create a new PublicInbox::DS subclass object for the given I<socket> which will
452 react to events on it during the C<EventLoop>.
453
454 This is normally (always?) called from your subclass via:
455
456   $class->SUPER::new($socket);
457
458 =cut
459 sub new {
460     my ($self, $sock, $exclusive) = @_;
461     $self = fields::new($self) unless ref $self;
462
463     $self->{sock}        = $sock;
464     my $fd = fileno($sock);
465
466     Carp::cluck("undef sock and/or fd in PublicInbox::DS->new.  sock=" . ($sock || "") . ", fd=" . ($fd || ""))
467         unless $sock && $fd;
468
469     $self->{fd}          = $fd;
470     $self->{write_buf}      = [];
471     $self->{write_buf_offset} = 0;
472     $self->{write_buf_size} = 0;
473     $self->{closed} = 0;
474
475     my $ev = $self->{event_watch} = POLLERR|POLLHUP|POLLNVAL;
476
477     _InitPoller();
478
479     if ($HaveEpoll) {
480         if ($exclusive) {
481             $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP|$EPOLLEXCLUSIVE;
482         }
483 retry:
484         if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
485             if ($!{EINVAL} && ($ev & $EPOLLEXCLUSIVE)) {
486                 $EPOLLEXCLUSIVE = 0; # old kernel
487                 $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP;
488                 goto retry;
489             }
490             die "couldn't add epoll watch for $fd: $!\n";
491         }
492     }
493     elsif ($HaveKQueue) {
494         # Add them to the queue but disabled for now
495         $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(),
496                         IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
497         $KQueue->EV_SET($fd, IO::KQueue::EVFILT_WRITE(),
498                         IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
499     }
500
501     Carp::cluck("PublicInbox::DS::new blowing away existing descriptor map for fd=$fd ($DescriptorMap{$fd})")
502         if $DescriptorMap{$fd};
503
504     $DescriptorMap{$fd} = $self;
505     return $self;
506 }
507
508
509 #####################################################################
510 ### I N S T A N C E   M E T H O D S
511 #####################################################################
512
513 =head2 C<< $obj->steal_socket() >>
514
515 Basically returns our socket and makes it so that we don't try to close it,
516 but we do remove it from epoll handlers.  THIS CLOSES $self.  It is the same
517 thing as calling close, except it gives you the socket to use.
518
519 =cut
520 sub steal_socket {
521     my PublicInbox::DS $self = $_[0];
522     return if $self->{closed};
523
524     # cleanup does most of the work of closing this socket
525     $self->_cleanup();
526
527     # now undef our internal sock and fd structures so we don't use them
528     my $sock = $self->{sock};
529     $self->{sock} = undef;
530     return $sock;
531 }
532
533 =head2 C<< $obj->close( [$reason] ) >>
534
535 Close the socket. The I<reason> argument will be used in debugging messages.
536
537 =cut
538 sub close {
539     my PublicInbox::DS $self = $_[0];
540     return if $self->{closed};
541
542     # print out debugging info for this close
543     if (DebugLevel) {
544         my ($pkg, $filename, $line) = caller;
545         my $reason = $_[1] || "";
546         warn "Closing \#$self->{fd} due to $pkg/$filename/$line ($reason)\n";
547     }
548
549     # this does most of the work of closing us
550     $self->_cleanup();
551
552     # defer closing the actual socket until the event loop is done
553     # processing this round of events.  (otherwise we might reuse fds)
554     if ($self->{sock}) {
555         push @ToClose, $self->{sock};
556         $self->{sock} = undef;
557     }
558
559     return 0;
560 }
561
562 ### METHOD: _cleanup()
563 ### Called by our closers so we can clean internal data structures.
564 sub _cleanup {
565     my PublicInbox::DS $self = $_[0];
566
567     # we're effectively closed; we have no fd and sock when we leave here
568     $self->{closed} = 1;
569
570     # we need to flush our write buffer, as there may
571     # be self-referential closures (sub { $client->close })
572     # preventing the object from being destroyed
573     $self->{write_buf} = [];
574
575     # if we're using epoll, we have to remove this from our epoll fd so we stop getting
576     # notifications about it
577     if ($HaveEpoll && $self->{fd}) {
578         if (epoll_ctl($Epoll, EPOLL_CTL_DEL, $self->{fd}, $self->{event_watch}) != 0) {
579             # dump_error prints a backtrace so we can try to figure out why this happened
580             $self->dump_error("epoll_ctl(): failure deleting fd=$self->{fd} during _cleanup(); $! (" . ($!+0) . ")");
581         }
582     }
583
584     # now delete from mappings.  this fd no longer belongs to us, so we don't want
585     # to get alerts for it if it becomes writable/readable/etc.
586     delete $PLCMap{$self->{fd}};
587
588     # we explicitly don't delete from DescriptorMap here until we
589     # actually close the socket, as we might be in the middle of
590     # processing an epoll_wait/etc that returned hundreds of fds, one
591     # of which is not yet processed and is what we're closing.  if we
592     # keep it in DescriptorMap, then the event harnesses can just
593     # looked at $pob->{closed} and ignore it.  but if it's an
594     # un-accounted for fd, then it (understandably) freak out a bit
595     # and emit warnings, thinking their state got off.
596
597     # and finally get rid of our fd so we can't use it anywhere else
598     $self->{fd} = undef;
599 }
600
601 =head2 C<< $obj->sock() >>
602
603 Returns the underlying IO::Handle for the object.
604
605 =cut
606 sub sock {
607     my PublicInbox::DS $self = shift;
608     return $self->{sock};
609 }
610
611 =head2 C<< $obj->write( $data ) >>
612
613 Write the specified data to the underlying handle.  I<data> may be scalar,
614 scalar ref, code ref (to run when there), or undef just to kick-start.
615 Returns 1 if writes all went through, or 0 if there are writes in queue. If
616 it returns 1, caller should stop waiting for 'writable' events)
617
618 =cut
619 sub write {
620     my PublicInbox::DS $self;
621     my $data;
622     ($self, $data) = @_;
623
624     # nobody should be writing to closed sockets, but caller code can
625     # do two writes within an event, have the first fail and
626     # disconnect the other side (whose destructor then closes the
627     # calling object, but it's still in a method), and then the
628     # now-dead object does its second write.  that is this case.  we
629     # just lie and say it worked.  it'll be dead soon and won't be
630     # hurt by this lie.
631     return 1 if $self->{closed};
632
633     my $bref;
634
635     # just queue data if there's already a wait
636     my $need_queue;
637
638     if (defined $data) {
639         $bref = ref $data ? $data : \$data;
640         if ($self->{write_buf_size}) {
641             push @{$self->{write_buf}}, $bref;
642             $self->{write_buf_size} += ref $bref eq "SCALAR" ? length($$bref) : 1;
643             return 0;
644         }
645
646         # this flag says we're bypassing the queue system, knowing we're the
647         # only outstanding write, and hoping we don't ever need to use it.
648         # if so later, though, we'll need to queue
649         $need_queue = 1;
650     }
651
652   WRITE:
653     while (1) {
654         return 1 unless $bref ||= $self->{write_buf}[0];
655
656         my $len;
657         eval {
658             $len = length($$bref); # this will die if $bref is a code ref, caught below
659         };
660         if ($@) {
661             if (UNIVERSAL::isa($bref, "CODE")) {
662                 unless ($need_queue) {
663                     $self->{write_buf_size}--; # code refs are worth 1
664                     shift @{$self->{write_buf}};
665                 }
666                 $bref->();
667
668                 # code refs are just run and never get reenqueued
669                 # (they're one-shot), so turn off the flag indicating the
670                 # outstanding data needs queueing.
671                 $need_queue = 0;
672
673                 undef $bref;
674                 next WRITE;
675             }
676             die "Write error: $@ <$bref>";
677         }
678
679         my $to_write = $len - $self->{write_buf_offset};
680         my $written = syswrite($self->{sock}, $$bref, $to_write,
681                                $self->{write_buf_offset});
682
683         if (! defined $written) {
684             if ($! == EPIPE) {
685                 return $self->close("EPIPE");
686             } elsif ($! == EAGAIN) {
687                 # since connection has stuff to write, it should now be
688                 # interested in pending writes:
689                 if ($need_queue) {
690                     push @{$self->{write_buf}}, $bref;
691                     $self->{write_buf_size} += $len;
692                 }
693                 $self->{write_set_watch} = 1 unless $self->{event_watch} & POLLOUT;
694                 $self->watch_write(1);
695                 return 0;
696             } elsif ($! == ECONNRESET) {
697                 return $self->close("ECONNRESET");
698             }
699
700             DebugLevel >= 1 && $self->debugmsg("Closing connection ($self) due to write error: $!\n");
701
702             return $self->close("write_error");
703         } elsif ($written != $to_write) {
704             DebugLevel >= 2 && $self->debugmsg("Wrote PARTIAL %d bytes to %d",
705                                                $written, $self->{fd});
706             if ($need_queue) {
707                 push @{$self->{write_buf}}, $bref;
708                 $self->{write_buf_size} += $len;
709             }
710             # since connection has stuff to write, it should now be
711             # interested in pending writes:
712             $self->{write_buf_offset} += $written;
713             $self->{write_buf_size} -= $written;
714             $self->on_incomplete_write;
715             return 0;
716         } elsif ($written == $to_write) {
717             DebugLevel >= 2 && $self->debugmsg("Wrote ALL %d bytes to %d (nq=%d)",
718                                                $written, $self->{fd}, $need_queue);
719             $self->{write_buf_offset} = 0;
720
721             if ($self->{write_set_watch}) {
722                 $self->watch_write(0);
723                 $self->{write_set_watch} = 0;
724             }
725
726             # this was our only write, so we can return immediately
727             # since we avoided incrementing the buffer size or
728             # putting it in the buffer.  we also know there
729             # can't be anything else to write.
730             return 1 if $need_queue;
731
732             $self->{write_buf_size} -= $written;
733             shift @{$self->{write_buf}};
734             undef $bref;
735             next WRITE;
736         }
737     }
738 }
739
740 sub on_incomplete_write {
741     my PublicInbox::DS $self = shift;
742     $self->{write_set_watch} = 1 unless $self->{event_watch} & POLLOUT;
743     $self->watch_write(1);
744 }
745
746 =head2 C<< $obj->read( $bytecount ) >>
747
748 Read at most I<bytecount> bytes from the underlying handle; returns scalar
749 ref on read, or undef on connection closed.
750
751 =cut
752 sub read {
753     my PublicInbox::DS $self = shift;
754     return if $self->{closed};
755     my $bytes = shift;
756     my $buf;
757     my $sock = $self->{sock};
758
759     # if this is too high, perl quits(!!).  reports on mailing lists
760     # don't seem to point to a universal answer.  5MB worked for some,
761     # crashed for others.  1MB works for more people.  let's go with 1MB
762     # for now.  :/
763     my $req_bytes = $bytes > 1048576 ? 1048576 : $bytes;
764
765     my $res = sysread($sock, $buf, $req_bytes, 0);
766     DebugLevel >= 2 && $self->debugmsg("sysread = %d; \$! = %d", $res, $!);
767
768     if (! $res && $! != EWOULDBLOCK) {
769         # catches 0=conn closed or undef=error
770         DebugLevel >= 2 && $self->debugmsg("Fd \#%d read hit the end of the road.", $self->{fd});
771         return undef;
772     }
773
774     return \$buf;
775 }
776
777 =head2 (VIRTUAL) C<< $obj->event_read() >>
778
779 Readable event handler. Concrete deriviatives of PublicInbox::DS should
780 provide an implementation of this. The default implementation will die if
781 called.
782
783 =cut
784 sub event_read  { die "Base class event_read called for $_[0]\n"; }
785
786 =head2 (VIRTUAL) C<< $obj->event_err() >>
787
788 Error event handler. Concrete deriviatives of PublicInbox::DS should
789 provide an implementation of this. The default implementation will die if
790 called.
791
792 =cut
793 sub event_err   { die "Base class event_err called for $_[0]\n"; }
794
795 =head2 (VIRTUAL) C<< $obj->event_hup() >>
796
797 'Hangup' event handler. Concrete deriviatives of PublicInbox::DS should
798 provide an implementation of this. The default implementation will die if
799 called.
800
801 =cut
802 sub event_hup   { die "Base class event_hup called for $_[0]\n"; }
803
804 =head2 C<< $obj->event_write() >>
805
806 Writable event handler. Concrete deriviatives of PublicInbox::DS may wish to
807 provide an implementation of this. The default implementation calls
808 C<write()> with an C<undef>.
809
810 =cut
811 sub event_write {
812     my $self = shift;
813     $self->write(undef);
814 }
815
816 =head2 C<< $obj->watch_read( $boolean ) >>
817
818 Turn 'readable' event notification on or off.
819
820 =cut
821 sub watch_read {
822     my PublicInbox::DS $self = shift;
823     return if $self->{closed} || !$self->{sock};
824
825     my $val = shift;
826     my $event = $self->{event_watch};
827
828     $event &= ~POLLIN if ! $val;
829     $event |=  POLLIN if   $val;
830
831     # If it changed, set it
832     if ($event != $self->{event_watch}) {
833         if ($HaveKQueue) {
834             $KQueue->EV_SET($self->{fd}, IO::KQueue::EVFILT_READ(),
835                             $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
836         }
837         elsif ($HaveEpoll) {
838             epoll_ctl($Epoll, EPOLL_CTL_MOD, $self->{fd}, $event)
839                 and $self->dump_error("couldn't modify epoll settings for $self->{fd} " .
840                                       "from $self->{event_watch} -> $event: $! (" . ($!+0) . ")");
841         }
842         $self->{event_watch} = $event;
843     }
844 }
845
846 =head2 C<< $obj->watch_write( $boolean ) >>
847
848 Turn 'writable' event notification on or off.
849
850 =cut
851 sub watch_write {
852     my PublicInbox::DS $self = shift;
853     return if $self->{closed} || !$self->{sock};
854
855     my $val = shift;
856     my $event = $self->{event_watch};
857
858     $event &= ~POLLOUT if ! $val;
859     $event |=  POLLOUT if   $val;
860
861     if ($val && caller ne __PACKAGE__) {
862         # A subclass registered interest, it's now responsible for this.
863         $self->{write_set_watch} = 0;
864     }
865
866     # If it changed, set it
867     if ($event != $self->{event_watch}) {
868         if ($HaveKQueue) {
869             $KQueue->EV_SET($self->{fd}, IO::KQueue::EVFILT_WRITE(),
870                             $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
871         }
872         elsif ($HaveEpoll) {
873             epoll_ctl($Epoll, EPOLL_CTL_MOD, $self->{fd}, $event)
874                 and $self->dump_error("couldn't modify epoll settings for $self->{fd} " .
875                                       "from $self->{event_watch} -> $event: $! (" . ($!+0) . ")");
876         }
877         $self->{event_watch} = $event;
878     }
879 }
880
881 =head2 C<< $obj->dump_error( $message ) >>
882
883 Prints to STDERR a backtrace with information about this socket and what lead
884 up to the dump_error call.
885
886 =cut
887 sub dump_error {
888     my $i = 0;
889     my @list;
890     while (my ($file, $line, $sub) = (caller($i++))[1..3]) {
891         push @list, "\t$file:$line called $sub\n";
892     }
893
894     warn "ERROR: $_[1]\n" .
895         "\t$_[0] = " . $_[0]->as_string . "\n" .
896         join('', @list);
897 }
898
899 =head2 C<< $obj->debugmsg( $format, @args ) >>
900
901 Print the debugging message specified by the C<sprintf>-style I<format> and
902 I<args>.
903
904 =cut
905 sub debugmsg {
906     my ( $self, $fmt, @args ) = @_;
907     confess "Not an object" unless ref $self;
908
909     chomp $fmt;
910     printf STDERR ">>> $fmt\n", @args;
911 }
912
913 =head2 C<< $obj->as_string() >>
914
915 Returns a string describing this socket.
916
917 =cut
918 sub as_string {
919     my PublicInbox::DS $self = shift;
920     my $rw = "(" . ($self->{event_watch} & POLLIN ? 'R' : '') .
921                    ($self->{event_watch} & POLLOUT ? 'W' : '') . ")";
922     my $ret = ref($self) . "$rw: " . ($self->{closed} ? "closed" : "open");
923     return $ret;
924 }
925
926 package PublicInbox::DS::Timer;
927 # [$abs_float_firetime, $coderef];
928 sub cancel {
929     $_[0][1] = undef;
930 }
931
932 1;
933
934 =head1 AUTHORS (Danga::Socket)
935
936 Brad Fitzpatrick <brad@danga.com> - author
937
938 Michael Granger <ged@danga.com> - docs, testing
939
940 Mark Smith <junior@danga.com> - contributor, heavy user, testing
941
942 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits