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