]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/KQNotify.pm
lock: reduce inotify wakeups
[public-inbox.git] / lib / PublicInbox / KQNotify.pm
1 # Copyright (C) 2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # implements the small subset of Linux::Inotify2 functionality we use
5 # using IO::KQueue on *BSD systems.
6 package PublicInbox::KQNotify;
7 use strict;
8 use IO::KQueue;
9 use PublicInbox::DSKQXS; # wraps IO::KQueue for fork-safe DESTROY
10
11 sub new {
12         my ($class) = @_;
13         bless { dskq => PublicInbox::DSKQXS->new, watch => {} }, $class;
14 }
15
16 sub watch {
17         my ($self, $path, $mask, $cb) = @_;
18         open(my $fh, '<', $path) or return;
19         my $ident = fileno($fh);
20         $self->{dskq}->{kq}->EV_SET($ident, # ident
21                 EVFILT_VNODE, # filter
22                 EV_ADD | EV_CLEAR, # flags
23                 $mask, # fflags
24                 0, 0); # data, udata
25         if ($mask == NOTE_WRITE) {
26                 $self->{watch}->{$ident} = [ $fh, $cb ];
27         } else {
28                 die "TODO Not implemented: $mask";
29         }
30         bless \$fh, 'PublicInbox::KQNotify::Watch';
31 }
32
33 # emulate Linux::Inotify::fileno
34 sub fileno { ${$_[0]->{dskq}->{kq}} }
35
36 # noop for Linux::Inotify2 compatibility.  Unlike inotify,
37 # kqueue doesn't seem to overflow since it's limited by the number of
38 # open FDs the process has
39 sub on_overflow {}
40
41 # noop for Linux::Inotify2 compatibility, we use `0' timeout for ->kevent
42 sub blocking {}
43
44 # behave like Linux::Inotify2::poll
45 sub poll {
46         my ($self) = @_;
47         my @kevents = $self->{dskq}->{kq}->kevent(0);
48         for my $kev (@kevents) {
49                 my $ident = $kev->[KQ_IDENT];
50                 my $mask = $kev->[KQ_FFLAGS];
51                 if (($mask & NOTE_WRITE) == NOTE_WRITE) {
52                         eval { $self->{watch}->{$ident}->[1]->() };
53                 }
54         }
55 }
56
57 package PublicInbox::KQNotify::Watch;
58 use strict;
59
60 sub cancel { close ${$_[0]} or die "close: $!" }
61
62 1;