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