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