]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/DS.pm
7bd5d42b9b2aaef8ab73acd356c4d66b6225d9ea
[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 = $KQueue->kevent($timeout);
432
433         foreach my $kev (@ret) {
434             my ($fd, $filter, $flags, $fflags) = @$kev;
435             my PublicInbox::DS $pob = $DescriptorMap{$fd};
436             if (!$pob) {
437                 if (my $code = $OtherFds{$fd}) {
438                     $code->($filter);
439                 }  else {
440                     warn "kevent() returned fd $fd for which we have no mapping.  removing.\n";
441                     POSIX::close($fd); # close deletes the kevent entry
442                 }
443                 next;
444             }
445
446             DebugLevel >= 1 && $class->DebugMsg("Event: fd=%d (%s), flags=%d \@ %s\n",
447                                                         $fd, ref($pob), $flags, time);
448
449             $pob->event_read  if $filter == IO::KQueue::EVFILT_READ()  && !$pob->{closed};
450             $pob->event_write if $filter == IO::KQueue::EVFILT_WRITE() && !$pob->{closed};
451             if ($flags ==  IO::KQueue::EV_EOF() && !$pob->{closed}) {
452                 if ($fflags) {
453                     $pob->event_err;
454                 } else {
455                     $pob->event_hup;
456                 }
457             }
458         }
459         return unless PostEventLoop();
460     }
461
462     exit(0);
463 }
464
465 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
466
467 Sets post loop callback function.  Pass a subref and it will be
468 called every time the event loop finishes.
469
470 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
471 and it will exit.
472
473 The callback function will be passed two parameters: \%DescriptorMap, \%OtherFds.
474
475 =cut
476 sub SetPostLoopCallback {
477     my ($class, $ref) = @_;
478
479     if (ref $class) {
480         # per-object callback
481         my PublicInbox::DS $self = $class;
482         if (defined $ref && ref $ref eq 'CODE') {
483             $PLCMap{$self->{fd}} = $ref;
484         } else {
485             delete $PLCMap{$self->{fd}};
486         }
487     } else {
488         # global callback
489         $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
490     }
491 }
492
493 # Internal function: run the post-event callback, send read events
494 # for pushed-back data, and close pending connections.  returns 1
495 # if event loop should continue, or 0 to shut it all down.
496 sub PostEventLoop {
497     # now we can close sockets that wanted to close during our event processing.
498     # (we didn't want to close them during the loop, as we didn't want fd numbers
499     #  being reused and confused during the event loop)
500     while (my $sock = shift @ToClose) {
501         my $fd = fileno($sock);
502
503         # close the socket.  (not a PublicInbox::DS close)
504         $sock->close;
505
506         # and now we can finally remove the fd from the map.  see
507         # comment above in _cleanup.
508         delete $DescriptorMap{$fd};
509     }
510
511
512     # by default we keep running, unless a postloop callback (either per-object
513     # or global) cancels it
514     my $keep_running = 1;
515
516     # per-object post-loop-callbacks
517     for my $plc (values %PLCMap) {
518         $keep_running &&= $plc->(\%DescriptorMap, \%OtherFds);
519     }
520
521     # now we're at the very end, call callback if defined
522     if (defined $PostLoopCallback) {
523         $keep_running &&= $PostLoopCallback->(\%DescriptorMap, \%OtherFds);
524     }
525
526     return $keep_running;
527 }
528
529 #####################################################################
530 ### PublicInbox::DS-the-object code
531 #####################################################################
532
533 =head2 OBJECT METHODS
534
535 =head2 C<< CLASS->new( $socket ) >>
536
537 Create a new PublicInbox::DS subclass object for the given I<socket> which will
538 react to events on it during the C<EventLoop>.
539
540 This is normally (always?) called from your subclass via:
541
542   $class->SUPER::new($socket);
543
544 =cut
545 sub new {
546     my ($self, $sock, $exclusive) = @_;
547     $self = fields::new($self) unless ref $self;
548
549     $self->{sock}        = $sock;
550     my $fd = fileno($sock);
551
552     Carp::cluck("undef sock and/or fd in PublicInbox::DS->new.  sock=" . ($sock || "") . ", fd=" . ($fd || ""))
553         unless $sock && $fd;
554
555     $self->{fd}          = $fd;
556     $self->{write_buf}      = [];
557     $self->{write_buf_offset} = 0;
558     $self->{write_buf_size} = 0;
559     $self->{closed} = 0;
560
561     my $ev = $self->{event_watch} = POLLERR|POLLHUP|POLLNVAL;
562
563     _InitPoller();
564
565     if ($HaveEpoll) {
566         if ($exclusive) {
567             $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP|$EPOLLEXCLUSIVE;
568         }
569 retry:
570         if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
571             if ($!{EINVAL} && ($ev & $EPOLLEXCLUSIVE)) {
572                 $EPOLLEXCLUSIVE = 0; # old kernel
573                 $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP;
574                 goto retry;
575             }
576             die "couldn't add epoll watch for $fd: $!\n";
577         }
578     }
579     elsif ($HaveKQueue) {
580         # Add them to the queue but disabled for now
581         $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(),
582                         IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
583         $KQueue->EV_SET($fd, IO::KQueue::EVFILT_WRITE(),
584                         IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
585     }
586
587     Carp::cluck("PublicInbox::DS::new blowing away existing descriptor map for fd=$fd ($DescriptorMap{$fd})")
588         if $DescriptorMap{$fd};
589
590     $DescriptorMap{$fd} = $self;
591     return $self;
592 }
593
594
595 #####################################################################
596 ### I N S T A N C E   M E T H O D S
597 #####################################################################
598
599 =head2 C<< $obj->steal_socket() >>
600
601 Basically returns our socket and makes it so that we don't try to close it,
602 but we do remove it from epoll handlers.  THIS CLOSES $self.  It is the same
603 thing as calling close, except it gives you the socket to use.
604
605 =cut
606 sub steal_socket {
607     my PublicInbox::DS $self = $_[0];
608     return if $self->{closed};
609
610     # cleanup does most of the work of closing this socket
611     $self->_cleanup();
612
613     # now undef our internal sock and fd structures so we don't use them
614     my $sock = $self->{sock};
615     $self->{sock} = undef;
616     return $sock;
617 }
618
619 =head2 C<< $obj->close( [$reason] ) >>
620
621 Close the socket. The I<reason> argument will be used in debugging messages.
622
623 =cut
624 sub close {
625     my PublicInbox::DS $self = $_[0];
626     return if $self->{closed};
627
628     # print out debugging info for this close
629     if (DebugLevel) {
630         my ($pkg, $filename, $line) = caller;
631         my $reason = $_[1] || "";
632         warn "Closing \#$self->{fd} due to $pkg/$filename/$line ($reason)\n";
633     }
634
635     # this does most of the work of closing us
636     $self->_cleanup();
637
638     # defer closing the actual socket until the event loop is done
639     # processing this round of events.  (otherwise we might reuse fds)
640     if ($self->{sock}) {
641         push @ToClose, $self->{sock};
642         $self->{sock} = undef;
643     }
644
645     return 0;
646 }
647
648 ### METHOD: _cleanup()
649 ### Called by our closers so we can clean internal data structures.
650 sub _cleanup {
651     my PublicInbox::DS $self = $_[0];
652
653     # we're effectively closed; we have no fd and sock when we leave here
654     $self->{closed} = 1;
655
656     # we need to flush our write buffer, as there may
657     # be self-referential closures (sub { $client->close })
658     # preventing the object from being destroyed
659     $self->{write_buf} = [];
660
661     # if we're using epoll, we have to remove this from our epoll fd so we stop getting
662     # notifications about it
663     if ($HaveEpoll && $self->{fd}) {
664         if (epoll_ctl($Epoll, EPOLL_CTL_DEL, $self->{fd}, $self->{event_watch}) != 0) {
665             # dump_error prints a backtrace so we can try to figure out why this happened
666             $self->dump_error("epoll_ctl(): failure deleting fd=$self->{fd} during _cleanup(); $! (" . ($!+0) . ")");
667         }
668     }
669
670     # now delete from mappings.  this fd no longer belongs to us, so we don't want
671     # to get alerts for it if it becomes writable/readable/etc.
672     delete $PLCMap{$self->{fd}};
673
674     # we explicitly don't delete from DescriptorMap here until we
675     # actually close the socket, as we might be in the middle of
676     # processing an epoll_wait/etc that returned hundreds of fds, one
677     # of which is not yet processed and is what we're closing.  if we
678     # keep it in DescriptorMap, then the event harnesses can just
679     # looked at $pob->{closed} and ignore it.  but if it's an
680     # un-accounted for fd, then it (understandably) freak out a bit
681     # and emit warnings, thinking their state got off.
682
683     # and finally get rid of our fd so we can't use it anywhere else
684     $self->{fd} = undef;
685 }
686
687 =head2 C<< $obj->sock() >>
688
689 Returns the underlying IO::Handle for the object.
690
691 =cut
692 sub sock {
693     my PublicInbox::DS $self = shift;
694     return $self->{sock};
695 }
696
697 =head2 C<< $obj->set_writer_func( CODEREF ) >>
698
699 Sets a function to use instead of C<syswrite()> when writing data to the socket.
700
701 =cut
702 sub set_writer_func {
703    my PublicInbox::DS $self = shift;
704    my $wtr = shift;
705    Carp::croak("Not a subref") unless !defined $wtr || UNIVERSAL::isa($wtr, "CODE");
706    $self->{writer_func} = $wtr;
707 }
708
709 =head2 C<< $obj->write( $data ) >>
710
711 Write the specified data to the underlying handle.  I<data> may be scalar,
712 scalar ref, code ref (to run when there), or undef just to kick-start.
713 Returns 1 if writes all went through, or 0 if there are writes in queue. If
714 it returns 1, caller should stop waiting for 'writable' events)
715
716 =cut
717 sub write {
718     my PublicInbox::DS $self;
719     my $data;
720     ($self, $data) = @_;
721
722     # nobody should be writing to closed sockets, but caller code can
723     # do two writes within an event, have the first fail and
724     # disconnect the other side (whose destructor then closes the
725     # calling object, but it's still in a method), and then the
726     # now-dead object does its second write.  that is this case.  we
727     # just lie and say it worked.  it'll be dead soon and won't be
728     # hurt by this lie.
729     return 1 if $self->{closed};
730
731     my $bref;
732
733     # just queue data if there's already a wait
734     my $need_queue;
735
736     if (defined $data) {
737         $bref = ref $data ? $data : \$data;
738         if ($self->{write_buf_size}) {
739             push @{$self->{write_buf}}, $bref;
740             $self->{write_buf_size} += ref $bref eq "SCALAR" ? length($$bref) : 1;
741             return 0;
742         }
743
744         # this flag says we're bypassing the queue system, knowing we're the
745         # only outstanding write, and hoping we don't ever need to use it.
746         # if so later, though, we'll need to queue
747         $need_queue = 1;
748     }
749
750   WRITE:
751     while (1) {
752         return 1 unless $bref ||= $self->{write_buf}[0];
753
754         my $len;
755         eval {
756             $len = length($$bref); # this will die if $bref is a code ref, caught below
757         };
758         if ($@) {
759             if (UNIVERSAL::isa($bref, "CODE")) {
760                 unless ($need_queue) {
761                     $self->{write_buf_size}--; # code refs are worth 1
762                     shift @{$self->{write_buf}};
763                 }
764                 $bref->();
765
766                 # code refs are just run and never get reenqueued
767                 # (they're one-shot), so turn off the flag indicating the
768                 # outstanding data needs queueing.
769                 $need_queue = 0;
770
771                 undef $bref;
772                 next WRITE;
773             }
774             die "Write error: $@ <$bref>";
775         }
776
777         my $to_write = $len - $self->{write_buf_offset};
778         my $written;
779         if (my $wtr = $self->{writer_func}) {
780             $written = $wtr->($bref, $to_write, $self->{write_buf_offset});
781         } else {
782             $written = syswrite($self->{sock}, $$bref, $to_write, $self->{write_buf_offset});
783         }
784
785         if (! defined $written) {
786             if ($! == EPIPE) {
787                 return $self->close("EPIPE");
788             } elsif ($! == EAGAIN) {
789                 # since connection has stuff to write, it should now be
790                 # interested in pending writes:
791                 if ($need_queue) {
792                     push @{$self->{write_buf}}, $bref;
793                     $self->{write_buf_size} += $len;
794                 }
795                 $self->{write_set_watch} = 1 unless $self->{event_watch} & POLLOUT;
796                 $self->watch_write(1);
797                 return 0;
798             } elsif ($! == ECONNRESET) {
799                 return $self->close("ECONNRESET");
800             }
801
802             DebugLevel >= 1 && $self->debugmsg("Closing connection ($self) due to write error: $!\n");
803
804             return $self->close("write_error");
805         } elsif ($written != $to_write) {
806             DebugLevel >= 2 && $self->debugmsg("Wrote PARTIAL %d bytes to %d",
807                                                $written, $self->{fd});
808             if ($need_queue) {
809                 push @{$self->{write_buf}}, $bref;
810                 $self->{write_buf_size} += $len;
811             }
812             # since connection has stuff to write, it should now be
813             # interested in pending writes:
814             $self->{write_buf_offset} += $written;
815             $self->{write_buf_size} -= $written;
816             $self->on_incomplete_write;
817             return 0;
818         } elsif ($written == $to_write) {
819             DebugLevel >= 2 && $self->debugmsg("Wrote ALL %d bytes to %d (nq=%d)",
820                                                $written, $self->{fd}, $need_queue);
821             $self->{write_buf_offset} = 0;
822
823             if ($self->{write_set_watch}) {
824                 $self->watch_write(0);
825                 $self->{write_set_watch} = 0;
826             }
827
828             # this was our only write, so we can return immediately
829             # since we avoided incrementing the buffer size or
830             # putting it in the buffer.  we also know there
831             # can't be anything else to write.
832             return 1 if $need_queue;
833
834             $self->{write_buf_size} -= $written;
835             shift @{$self->{write_buf}};
836             undef $bref;
837             next WRITE;
838         }
839     }
840 }
841
842 sub on_incomplete_write {
843     my PublicInbox::DS $self = shift;
844     $self->{write_set_watch} = 1 unless $self->{event_watch} & POLLOUT;
845     $self->watch_write(1);
846 }
847
848 =head2 C<< $obj->read( $bytecount ) >>
849
850 Read at most I<bytecount> bytes from the underlying handle; returns scalar
851 ref on read, or undef on connection closed.
852
853 =cut
854 sub read {
855     my PublicInbox::DS $self = shift;
856     return if $self->{closed};
857     my $bytes = shift;
858     my $buf;
859     my $sock = $self->{sock};
860
861     # if this is too high, perl quits(!!).  reports on mailing lists
862     # don't seem to point to a universal answer.  5MB worked for some,
863     # crashed for others.  1MB works for more people.  let's go with 1MB
864     # for now.  :/
865     my $req_bytes = $bytes > 1048576 ? 1048576 : $bytes;
866
867     my $res = sysread($sock, $buf, $req_bytes, 0);
868     DebugLevel >= 2 && $self->debugmsg("sysread = %d; \$! = %d", $res, $!);
869
870     if (! $res && $! != EWOULDBLOCK) {
871         # catches 0=conn closed or undef=error
872         DebugLevel >= 2 && $self->debugmsg("Fd \#%d read hit the end of the road.", $self->{fd});
873         return undef;
874     }
875
876     return \$buf;
877 }
878
879 =head2 (VIRTUAL) C<< $obj->event_read() >>
880
881 Readable event handler. Concrete deriviatives of PublicInbox::DS should
882 provide an implementation of this. The default implementation will die if
883 called.
884
885 =cut
886 sub event_read  { die "Base class event_read called for $_[0]\n"; }
887
888 =head2 (VIRTUAL) C<< $obj->event_err() >>
889
890 Error event handler. Concrete deriviatives of PublicInbox::DS should
891 provide an implementation of this. The default implementation will die if
892 called.
893
894 =cut
895 sub event_err   { die "Base class event_err called for $_[0]\n"; }
896
897 =head2 (VIRTUAL) C<< $obj->event_hup() >>
898
899 'Hangup' event handler. Concrete deriviatives of PublicInbox::DS should
900 provide an implementation of this. The default implementation will die if
901 called.
902
903 =cut
904 sub event_hup   { die "Base class event_hup called for $_[0]\n"; }
905
906 =head2 C<< $obj->event_write() >>
907
908 Writable event handler. Concrete deriviatives of PublicInbox::DS may wish to
909 provide an implementation of this. The default implementation calls
910 C<write()> with an C<undef>.
911
912 =cut
913 sub event_write {
914     my $self = shift;
915     $self->write(undef);
916 }
917
918 =head2 C<< $obj->watch_read( $boolean ) >>
919
920 Turn 'readable' event notification on or off.
921
922 =cut
923 sub watch_read {
924     my PublicInbox::DS $self = shift;
925     return if $self->{closed} || !$self->{sock};
926
927     my $val = shift;
928     my $event = $self->{event_watch};
929
930     $event &= ~POLLIN if ! $val;
931     $event |=  POLLIN if   $val;
932
933     # If it changed, set it
934     if ($event != $self->{event_watch}) {
935         if ($HaveKQueue) {
936             $KQueue->EV_SET($self->{fd}, IO::KQueue::EVFILT_READ(),
937                             $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
938         }
939         elsif ($HaveEpoll) {
940             epoll_ctl($Epoll, EPOLL_CTL_MOD, $self->{fd}, $event)
941                 and $self->dump_error("couldn't modify epoll settings for $self->{fd} " .
942                                       "from $self->{event_watch} -> $event: $! (" . ($!+0) . ")");
943         }
944         $self->{event_watch} = $event;
945     }
946 }
947
948 =head2 C<< $obj->watch_write( $boolean ) >>
949
950 Turn 'writable' event notification on or off.
951
952 =cut
953 sub watch_write {
954     my PublicInbox::DS $self = shift;
955     return if $self->{closed} || !$self->{sock};
956
957     my $val = shift;
958     my $event = $self->{event_watch};
959
960     $event &= ~POLLOUT if ! $val;
961     $event |=  POLLOUT if   $val;
962
963     if ($val && caller ne __PACKAGE__) {
964         # A subclass registered interest, it's now responsible for this.
965         $self->{write_set_watch} = 0;
966     }
967
968     # If it changed, set it
969     if ($event != $self->{event_watch}) {
970         if ($HaveKQueue) {
971             $KQueue->EV_SET($self->{fd}, IO::KQueue::EVFILT_WRITE(),
972                             $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
973         }
974         elsif ($HaveEpoll) {
975             epoll_ctl($Epoll, EPOLL_CTL_MOD, $self->{fd}, $event)
976                 and $self->dump_error("couldn't modify epoll settings for $self->{fd} " .
977                                       "from $self->{event_watch} -> $event: $! (" . ($!+0) . ")");
978         }
979         $self->{event_watch} = $event;
980     }
981 }
982
983 =head2 C<< $obj->dump_error( $message ) >>
984
985 Prints to STDERR a backtrace with information about this socket and what lead
986 up to the dump_error call.
987
988 =cut
989 sub dump_error {
990     my $i = 0;
991     my @list;
992     while (my ($file, $line, $sub) = (caller($i++))[1..3]) {
993         push @list, "\t$file:$line called $sub\n";
994     }
995
996     warn "ERROR: $_[1]\n" .
997         "\t$_[0] = " . $_[0]->as_string . "\n" .
998         join('', @list);
999 }
1000
1001 =head2 C<< $obj->debugmsg( $format, @args ) >>
1002
1003 Print the debugging message specified by the C<sprintf>-style I<format> and
1004 I<args>.
1005
1006 =cut
1007 sub debugmsg {
1008     my ( $self, $fmt, @args ) = @_;
1009     confess "Not an object" unless ref $self;
1010
1011     chomp $fmt;
1012     printf STDERR ">>> $fmt\n", @args;
1013 }
1014
1015 =head2 C<< $obj->as_string() >>
1016
1017 Returns a string describing this socket.
1018
1019 =cut
1020 sub as_string {
1021     my PublicInbox::DS $self = shift;
1022     my $rw = "(" . ($self->{event_watch} & POLLIN ? 'R' : '') .
1023                    ($self->{event_watch} & POLLOUT ? 'W' : '') . ")";
1024     my $ret = ref($self) . "$rw: " . ($self->{closed} ? "closed" : "open");
1025     return $ret;
1026 }
1027
1028 sub _undef {
1029     return undef unless $ENV{DS_DEBUG};
1030     my $msg = shift || "";
1031     warn "PublicInbox::DS: $msg\n";
1032     return undef;
1033 }
1034
1035 package PublicInbox::DS::Timer;
1036 # [$abs_float_firetime, $coderef];
1037 sub cancel {
1038     $_[0][1] = undef;
1039 }
1040
1041 1;
1042
1043 =head1 AUTHORS (Danga::Socket)
1044
1045 Brad Fitzpatrick <brad@danga.com> - author
1046
1047 Michael Granger <ged@danga.com> - docs, testing
1048
1049 Mark Smith <junior@danga.com> - contributor, heavy user, testing
1050
1051 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits