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