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