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