]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/DSKQXS.pm
listener: use edge-triggered notifications
[public-inbox.git] / lib / PublicInbox / DSKQXS.pm
1 # Copyright (C) 2019 all contributors <meta@public-inbox.org>
2 # Licensed the same as Danga::Socket (and Perl5)
3 # License: GPL-1.0+ or Artistic-1.0-Perl
4 #  <https://www.gnu.org/licenses/gpl-1.0.txt>
5 #  <https://dev.perl.org/licenses/artistic.html>
6 #
7 # kqueue support via IO::KQueue XS module.  This makes kqueue look
8 # like epoll to simplify the code in DS.pm.  This is NOT meant to be
9 # an all encompassing emulation of epoll via IO::KQueue, but just to
10 # support cases public-inbox-nntpd/httpd care about.
11 # A pure-Perl version using syscall() is planned, and it should be
12 # faster due to the lack of syscall overhead.
13 package PublicInbox::DSKQXS;
14 use strict;
15 use warnings;
16 use parent qw(IO::KQueue);
17 use parent qw(Exporter);
18 use IO::KQueue;
19 use PublicInbox::Syscall qw(EPOLLONESHOT EPOLLIN EPOLLOUT EPOLLET
20         EPOLL_CTL_DEL);
21 our @EXPORT_OK = qw(epoll_ctl epoll_wait);
22 my $owner_pid = -1; # kqueue is close-on-fork (yes, fork, not exec)
23
24 # map EPOLL* bits to kqueue EV_* flags for EV_SET
25 sub kq_flag ($$) {
26         my ($bit, $ev) = @_;
27         if ($ev & $bit) {
28                 my $fl = EV_ADD | EV_ENABLE;
29                 $fl |= EV_CLEAR if $fl & EPOLLET;
30                 ($ev & EPOLLONESHOT) ? ($fl | EV_ONESHOT) : $fl;
31         } else {
32                 EV_ADD | EV_DISABLE;
33         }
34 }
35
36 sub new {
37         my ($class) = @_;
38         die 'non-singleton use not supported' if $owner_pid == $$;
39         $owner_pid = $$;
40         $class->SUPER::new;
41 }
42
43 sub epoll_ctl {
44         my ($self, $op, $fd, $ev) = @_;
45         if ($op != EPOLL_CTL_DEL) {
46                 $self->EV_SET($fd, EVFILT_READ, kq_flag(EPOLLIN, $ev));
47                 $self->EV_SET($fd, EVFILT_WRITE, kq_flag(EPOLLOUT, $ev));
48         }
49         0;
50 }
51
52 sub epoll_wait {
53         my ($self, $maxevents, $timeout_msec, $events) = @_;
54         @$events = eval { $self->kevent($timeout_msec) };
55         if (my $err = $@) {
56                 # workaround https://rt.cpan.org/Ticket/Display.html?id=116615
57                 if ($err =~ /Interrupted system call/) {
58                         @$events = ();
59                 } else {
60                         die $err;
61                 }
62         }
63         # caller only cares for $events[$i]->[0]
64         scalar(@$events);
65 }
66
67 sub DESTROY {
68         my ($self) = @_;
69         if ($owner_pid == $$) {
70                 POSIX::close($$self);
71                 $owner_pid = -1;
72         }
73 }
74
75 1;