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