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