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