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