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