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